求教导怎么用 Jest 测试 Koa2 Api Server
发布于 8 年前 作者 Rukeith 4846 次预览 最后一次回复是 8 年前 来自 问答
最近想要用 Koa2 来制作自己的部落格 Backend api server 先简单地写出一些功能后,想使用 Jest 来做测试,但是发现了许多问题 希望有大大能给小弟一些建议 小弟遇到的问题有以下几个,目前一直都没有好的解法
- 没办法测试 i18n 和 MongoDB:不知道是不是 jest 测试启动的方法不一样,本来应该在 entry file 中导入的 middleware i18n 没有启动到。另外 mongodb 也没有启动到,变得这两边我都要判断 NODE_ENV=test 来略过
- 没办法直接使用 toThrowError 来验证 new Error 的物件
- 没办法测试 api,不知道为什么一直没办法测试 api,有找寻过网路上的范例。但是在 route 那边 log 却没有东西印出来
- 跑测试时 port 会发生互抢的问题,目前不知道问题点是什么,只能先判断如果 port 已被使用就略过
以下是小弟的项目位址 和 jest.config.js 如果有写法上的建议,感谢各位大大交流指教 repository
module.exports = {
bail: true, // Stop test when first test fail
collectCoverage: true,
collectCoverageFrom: ['**/*.{js}'],
coverageDirectory: '<rootDir>/public/coverage',
coveragePathIgnorePatterns: [
'<rootDir>/views/',
'<rootDir>/config/',
'<rootDir>/public/',
'<rootDir>/jest.config.js/',
'<rootDir>/node_modules/',
],
coverageReporters: ['lcov', 'text', 'text-summary'],
coverageThreshold: {
global: {
lines: 100,
branches: 100,
functions: 100,
statements: 100,
},
},
clearMocks: true,
resetMocks: true,
testEnvironment: 'node',
setupFiles: ['<rootDir>/index.js'],
verbose: true,
watchPathIgnorePatterns: [
'<rootDir>/LICENSE',
'<rootDir>/.eslintrc',
'<rootDir>/.gitignore',
'<rootDir>/.eslintignore',
'<rootDir>/node_modules/',
],
};
4 回复
@i5ting 启动 mongodb 是因为我想做 e2e 的测试,api 的话我是已经用了 supertest 了,但还是无法在 route 层收到 log
@Rukeith e2e是ui测试,为啥要依赖mongodb么?
@i5ting 我 end to end test 是想用在 api 测试上 确定从 api 到写到 mongodb 是没有问题的这样