我試圖使用jest和supertest來測驗一個Express應用程式的端點。以下是我的檔案:
// backend/tests/integration.test.ts
const server = require('./server')。
const supertest = require('supertest')。
const appTest = supertest(server);
describe('集成測驗', () => {
it('GET /api/ping', async ( ) =>{
const expected = { status: 200, body: { success: true } }
const res = await appTest.get('/api/ping')。
expect(res.status).toEqual( expected.status)。
expect(res.body).toEqual( expected.body)。
});
});
//backend/server.ts
import應用程式 from './src/app'。
const PORT = 3000;
const server = app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`) 。
});
export default server。
// backend/src/app.ts
const express = require('express') 。
const app = express()。
app.get('/api/ping', (req, res) => /span> {
res.status(200).json({
'success': true。
});
});
export default app;
我一直收到這樣的錯誤:
TypeError: app.address不是一個function。
而堆疊跟蹤顯示,錯誤出現在這一行:
8 | it('GET /api/ping', async()=> {
9 | const expected = { status: 200, body: { success: true } }
> 10 | const res = await appTest.get('/api/ping')。
| ^
11 | expect(res.status).toEqual( expected.status) 。
12 | expect(res.body).toEqual( expected.body) 。
13 | })。)
我的配置看起來像:
// package.json
...
"scripts": { > ...
"test": "jest"
}
// jest.config.js
module.exports = {
preset: 'ts-jest',
modulePathIgnorePatterns: ["<rootDir>/dist/"] 。
transform: {
'^. /*. (ts|tsx)?$'。'ts-jest'。
}
};
// babel.config.js
module.exports = {
presets: ['@babel/preset-env']
};
// tsconfig.json.
{>
"compilerOptions": {>
"模塊": "commonjs",
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist"
},
"lib": ["es2015"],
"exclude": [/span>
".../node_modules"/span>
],
"include": [/span>
"./**/*.ts"
]
}
我不知道為什么會發生這種情況。我試著在谷歌上搜索了一下,并在堆疊溢位上閱讀了關于超時錯誤的內容,但沒有任何效果。
uj5u.com熱心網友回復:
在backend/tests/integration.test.ts中,只需使用沒有http.createServer
應該進行的修改:
<醇>const appTest = supertest(http.createServer(server));
使用 const appTest = supertest(server);it('GET /api/ping', async () => {...}allowJs: true,package.json
{
"name": "node",
"版本": "1.0.0"。
"描述": "",
"main": "index.js",
"scripts": {
"test": "jest"。
},
"author": "",
"許可證": "ISC"。
"依賴性": {
"babel": "^6.23.0",
"express": "^4.17.1",
"jest": "^27.2.0",
"supertest": "^6.1.6",
"ts-jest": "^27.0.5".
},
"devDependencies": {
"@types/jest"。"^27.0.1"。
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/327654.html
標籤:
