我已经完成了我的快速服务器的创建,并且正在使用Jest + Supertest来测试我的终结点并测试我的猫鼬数据库的所有CRUD操作。到目前为止,我什至无法在测试中创建新用户。
代码:
//server.spec.js
const supertest = require('supertest');
const server = require('./server');
describe('server.js', () => {
describe('GET /', () => {
it('should connect to server responding w/ 200', (done) => {
return supertest(server)
.get('/')
.then(res => {
expect(res.status).toBe(200);
done();
});
});
});
describe('/api/users/', () => {
it('should create a new user', async () => {
return await supertest(server)
.post('/api/users/register')
.send({ username: "jest", email: "jest@jest.com", password: "jestjest" })
.set("Accept", "application/json")
.then(res => {
console.log(res.body)
expect(res.status).toBe(201)
})
})
});
});
控制台输出:
FAIL src/server.spec.js (8.573 s)
server.js
GET /
√ should connect to server responding w/ 200 (231 ms)
/api/users/
× should create a new user (5005 ms)
● server.js › /api/users/ › should create a new user
: Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:
17 | it('should create a new user', async () => {
18 | return await supertest(server)
> 19 | .post('/api/users/register')
| ^
20 | .send({ username: "jest", email: "jest@jest.com", password: "jestjest" })
21 | .set("Accept", "application/json")
22 | .then(res => {
at new Spec (node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
at Suite.describe (src/server.spec.js:19:9)
at Suite.Object.<anonymous>.describe (src/server.spec.js:18:5)
at Object.<anonymous> (src/server.spec.js:6:1)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 passed, 2 total
Snapshots: 0 total
Time: 8.61 s, estimated 9 s
Ran all test suites related to changed files.
Watch Usage: Press w to show more.(node:26872) UnhandledPromiseRejectionWarning: Error: Caught error after test environment was torn down
我尝试了不同类型的解决方案,但没有成功。
##编辑## 感谢@Estus Flask为我提供答案。 我忘了添加数据库。