Ria*_*aco 7 express typescript supertest jestjs
我目前正在制作一个带有打字稿、节点、快递的 API,并使用 jest 和 supertest 进行测试。我在使用 Javascript 时没有问题,但我最近将我的项目文件从 JS 更改为 TS,包括测试文件,当我开始测试时,我在所有测试套件中的超级测试请求部分都收到以下错误,这是其中之一当我开始测试时,我的终端上的测试套件。
TypeError: app.address is not a function
37 | it("should return 400 if email is invalid", async () => {
38 | const res = await request(server)
> 39 | .post("/api/users/auth/register")
| ^
40 | .send({
41 | email: "nomail",
42 | password: "validpassword123",
Run Code Online (Sandbox Code Playgroud)
这是我的测试文件auth.test.ts:
import * as request from 'supertest';
import { User } from '../../../../src/models/User';
import * as mongoose from 'mongoose';
import getKeys from '../../../../src/config/keys';
describe("/api/users/auth", () => {
let server;
let accessToken = "Bearer accessToken";
let email;
let password;
beforeAll(async () => {
server = import('../../../../src/index')
await mongoose.connect(getKeys().mongoURI);
})
afterAll(async () => {
await server.close();
await mongoose.disconnect();
})
it("should return 400 if email is invalid", async () => {
const res = await request(server)
.post("/api/users/auth/register")
.send({
email: "nomail",
password: "validpassword123",
name: "name"
});
expect(res.status).toBe(400);
expect(res.body).toHaveProperty('errArray')
});
}
Run Code Online (Sandbox Code Playgroud)
这是我的 src/index.ts 文件,它是入口点。
import * as express from 'express';
import * as passport from 'passport';
import * as bodyParser from 'body-parser';
import * as path from 'path';
import * as session from 'express-session';
import getKeys from './config/keys';
const port = 3001 || process.env.PORT;
const server = app.listen(port, () =>
console.log(`Server running on port ${port}`)
);
export default server;
Run Code Online (Sandbox Code Playgroud)
我尝试将导出和导入服务器语法更改为所有 commonjs 语法,并安装和设置与此相关的所有依赖项,包括 @types/supertest、@types/jest、ts-jest,这是我的设置 jest.config.js
module.exports = {
verbose: true,
testURL: 'http://localhost',
testEnvironment: "node",
roots: [
"<rootDir>"
],
transform: {
"^.+\\.tsx?$": "ts-jest"
},
testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
globals: {
"ts-jest": {
"tsConfigFile": "tsconfig.json"
}
},
moduleFileExtensions: [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
}
Run Code Online (Sandbox Code Playgroud)
配置文件
{
"compilerOptions": {
"outDir": "./dist",
"moduleResolution": "node",
"sourceMap": true,
"module": "commonjs",
"allowJs": true,
"target": "es5",
"noUnusedParameters": false,
"allowUnreachableCode": true,
"allowUnusedLabels": true,
"types": [
"jest",
"node",
"express",
"mongoose",
"body-parser",
"supertest"
],
"lib": [
"es2015"
]
},
"include": [
"./src/**/*",
"index.ts"
],
"exclude": [
"./node_modules",
"**/*.spec.ts",
"**/*.test.ts"
]
}
Run Code Online (Sandbox Code Playgroud)
包.json
"scripts": {
"test": "jest --watchAll --runInBand",
"coverage": "jest --coverage",
"start": "ts-node src/index.ts",
"server": "./node_modules/nodemon/bin/nodemon.js",
"client": "npm start --prefix ../client",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
"devDependencies": {
"@types/body-parser": "^1.17.0",
"@types/express": "^4.16.0",
"@types/jest": "^23.3.12",
"@types/mongoose": "^5.3.7",
"@types/node": "^10.12.18",
"@types/supertest": "^2.0.7",
"jest": "^23.6.0",
"nodemon": "^1.18.9",
"supertest": "^3.3.0",
"ts-jest": "^23.10.5",
"ts-node": "^7.0.1",
"typescript": "^3.2.2"
}
Run Code Online (Sandbox Code Playgroud)
原因是你server传入的supertest是undefined。supertest将app.address()在内部使用,请参阅这一行。这就是它抛出错误的原因:
\n\n\n类型错误:app.address 不是函数
\n
如果你想server动态导入,你应该改变:
let server;\nbeforeAll(async () => {\n server = import(\'../../../../src/index\')\n})\nRun Code Online (Sandbox Code Playgroud)\n\n到:
\n\nlet server;\nbeforeAll(async () => {\n const mod = await import(\'../../../../src/index\');\n server = (mod as any).default;\n});\nRun Code Online (Sandbox Code Playgroud)\n\n例如
\n\nindex.ts:
import express from \'express\';\n\nconst app = express();\n\napp.post(\'/api/users/auth/register\', (req, res) => {\n res.status(400).json({ errArray: [] });\n});\n\nconst port = 3001 || process.env.PORT;\nconst server = app.listen(port, () => console.log(`Server running on port ${port}`));\n\nexport default server;\nRun Code Online (Sandbox Code Playgroud)\n\nindex.test.ts:
import request from \'supertest\';\n\ndescribe(\'/api/users/auth\', () => {\n let server;\n beforeAll(async () => {\n const mod = await import(\'./\');\n server = (mod as any).default;\n });\n\n afterAll((done) => {\n if (server) {\n server.close(done);\n }\n });\n\n it(\'should return 400 if email is invalid\', async () => {\n const res = await request(server)\n .post(\'/api/users/auth/register\')\n .send({\n email: \'nomail\',\n password: \'validpassword123\',\n name: \'name\',\n });\n\n expect(res.status).toBe(400);\n expect(res.body).toHaveProperty(\'errArray\');\n });\n});\nRun Code Online (Sandbox Code Playgroud)\n\n集成测试结果与覆盖率报告:
\n\n\xe2\x98\x81 jest-codelab [master] \xe2\x9a\xa1 npx jest --coverage --verbose /Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/54230886/index.test.ts\n PASS src/stackoverflow/54230886/index.test.ts (10.306s)\n /api/users/auth\n \xe2\x9c\x93 should return 400 if email is invalid (56ms)\n\n console.log src/stackoverflow/54230886/index.ts:437\n Server running on port 3001\n\n----------|----------|----------|----------|----------|-------------------|\nFile | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |\n----------|----------|----------|----------|----------|-------------------|\nAll files | 100 | 50 | 100 | 100 | |\n index.ts | 100 | 50 | 100 | 100 | 9 |\n----------|----------|----------|----------|----------|-------------------|\nTest Suites: 1 passed, 1 total\nTests: 1 passed, 1 total\nSnapshots: 0 total\nTime: 11.875s\nRun Code Online (Sandbox Code Playgroud)\n\n源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/54230886
\n| 归档时间: |
|
| 查看次数: |
3422 次 |
| 最近记录: |