我正在使用Node.js Express服务器上的Jest进行一些测试,但是我不知道如何测试嵌套在try / catch块中的调用。
这是我的server.js的一部分:
const start = async () => {
try {
if (process.env.NODE_ENV) {
await db.sync({ force: false });
}
...
app.get("/", (request, response) => {
response.send("Please feel free to use our api with /api");
});
...
app.listen(port, () => {
console.log(`Server running on port ${port}`);
return app;
});
} catch (err) {
console.log(err.message);
}
};
export default new Promise ( async () => {
return await start();
});
在这里,我想测试什么是app.listen()
状态代码,但是我对测试仍然不那么熟悉。
有什么建议吗?
这是我写的测试:
const request = require('supertest');
const app = require('../server');
describe('Test the root path', ()=>{
test("GET method returns status code 200", ()=>{
request(app).get('/').then( response =>{
expect(response.statusCode).toBe(200);
});
});
})
我认为app
不是我期望的,因为Jest告诉我app.address
不是函数,所以我的export default new Promise
不是正确的解决方案。
对不起,如果这看起来很混乱,希望您能提供帮助!
答案 0 :(得分:0)
这是解决方案:
server.js
:
const express = require('express');
const app = express();
const port = 3000;
const db = {
async sync(options) {},
};
const start = async () => {
try {
if (process.env.NODE_ENV) {
await db.sync({ force: false });
}
app.get('/', (request, response) => {
response.send('Please feel free to use our api with /api');
});
return app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
} catch (err) {
console.log(err.message);
}
};
export default start;
server.test.js
:
import request from 'supertest';
import start from './server';
describe('Test the root path', () => {
let server;
beforeAll(async () => {
server = await start();
});
afterAll((done) => {
server.close(done);
});
test('GET method returns status code 200', () => {
expect.assertions(1);
return request(server)
.get('/')
.then((response) => {
expect(response.statusCode).toBe(200);
});
});
});
具有覆盖率报告的集成测试结果:
PASS src/stackoverflow/55986832/server.test.js
Test the root path
✓ GET method returns status code 200 (45ms)
console.log src/stackoverflow/55986832/server.js:3342
Server running on port 3000
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 92.31 | 50 | 100 | 92.31 | |
server.js | 92.31 | 50 | 100 | 92.31 | 22 |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.075s, estimated 10s
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55986832