【问题标题】:Jest Test failing for API endpoint with 404 errorAPI 端点的 Jest 测试失败并出现 404 错误
【发布时间】:2021-02-14 05:52:01
【问题描述】:
  • 我正在尝试在具有 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

我的测试/后端/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',
  ],
}

有人可以提出测试失败的原因

【问题讨论】:

    标签: vue.js jestjs nuxt.js supertest


    【解决方案1】:

    在我的情况下,这是因为开玩笑的配置。

    我的 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      • 2015-09-19
      相关资源
      最近更新 更多