Jest测试失败,API端点出现404错误

问题描述

  • 我正在尝试在具有API路由的nuxt中测试我的serverMiddleware
  • 它只有一个路由/ api / v1 / test,它返回一个json true

我的api / index.js文件

import express from 'express'

const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.get('/test',(req,res) => res.json(true))
export default {
  path: '/api/v1',handler: app,}
  • 这是我的api.spec.js文件,其中包含返回404的测试
  • 如果我测试路线,则返回200

我的test / backend / api.spec.js文件

import { resolve } from 'path'
import { Nuxt,Builder } from 'nuxt'
import supertest from 'supertest'

// We keep the nuxt and server instance
// So we can close them at the end of the test
let nuxt = null

// Init Nuxt.js and create a server listening on localhost:4000
beforeAll(async () => {
  const config = {
    dev: process.env.NODE_ENV !== 'production',rootDir: resolve(__dirname,'../','../'),mode: 'universal',}

  nuxt = new Nuxt(config)

  await new Builder(nuxt).build()

  await nuxt.server.listen(3000,'localhost')
},30000)

// Close server and ask nuxt to stop listening to file changes
afterall(() => {
  nuxt.close()
})

describe('GET /api/v1/test',() => {
  test('returns status code 200',(done) => {
    supertest(nuxt.server.app).get('/api/v1/test').expect(200,done)
  })
})

我的jest.config.js文件

module.exports = {
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1','^~/(.*)$': '<rootDir>/$1','^vue$': 'vue/dist/vue.common.js',},modulefileExtensions: ['js','vue','json'],transform: {
    '^.+\\.js$': 'babel-jest','.*\\.(vue)$': 'vue-jest',collectCoverage: true,collectCoverageFrom: [
    '<rootDir>/components/**/*.vue','<rootDir>/pages/**/*.vue',],}

有人可以建议为什么测试失败

解决方法

就我而言,这是因为 jest 配置。

我的 jest.config.js

testEnvironment: 'jsdom'

api.test(spec).file 需要 node 环境。 我没有修改它。相反,我修改了 api.test.js 文件。

我刚刚在文件头部添加了下面的注释代码。 解决了)我的 api.test.js

/**
* @jest-environment node
*/

链接:https://jestjs.io/docs/configuration#testenvironment-string

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...