Skip to main content

单元测试

yarn add -D jest supertest ts-jest @types/jest @types/supertest

设置 jest 配置: jest.config.js

/* eslint-disable no-undef */module.exports = {  moduleFileExtensions: ['js', 'jsx', 'json', 'ts', 'tsx'],  verbose: true,  collectCoverage: false,  roots: ['<rootDir>/__tests__'],  collectCoverageFrom: ['**/*.{ts,js}', '!**/node_modules/**', '!**/build/**', '!**/coverage/**'],  transform: {    '\\.ts$': '<rootDir>/node_modules/ts-jest/preprocessor.js',  },  coverageThreshold: {    global: {      branches: 100,      functions: 100,      lines: 100,      statements: 100,    },  },  coverageReporters: ['text', 'text-summary'],  // testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(js|ts)x?$', // __tests__ 下的所有文件  testRegex: '(\\.|/)(test|spec)\\.(js|ts)x?$',  testPathIgnorePatterns: ['/node_modules/', '/build/', '/coverage/'],  testTimeout: 5000,}

package.json 添加命令:

"test": "export NODE_ENV=uniTest && jest --runInBand --forceExit --colors --detectOpenHandles --silent"

unitTest 环境下不直接运行 app server.ts:

if (process.env.NODE_ENV !== 'uniTest') {  app.listen(port, () => {    console.log(`Example app listening at http://localhost:${port}`)  })}

添加测试项:#

__tests__/_server.ts:

import supertest from "supertest"import app from "../src/server"
export default supertest(app)

__tests__/routers/test.test.ts

import server from '../_server'
describe('routers/test', () => {  it('should success', async () => {    const response = await server.get('/test')    expect(response.status).toEqual(200)    expect(JSON.parse(response.text).code).toEqual(200)  })})

跑测试#

yarn run test