代码之家  ›  专栏  ›  技术社区  ›  PirateApp

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

  •  0
  • PirateApp  · 技术社区  · 5 年前
    • 我正在尝试在具有API路由的nuxt中测试我的服务器中间件
    • 它有一个单一的路由/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',
      ],
    }
    

    有人能告诉我为什么考试不及格吗

    0 回复  |  直到 5 年前
        1
  •  1
  •   rkJun    5 年前

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

    我的jest.config.js

    testEnvironment: 'jsdom'
    

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

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

    /**
    * @jest-environment node
    */
    

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

    推荐文章