我正在尝试使用mocha / chai / supertest进行基本测试。当我使用命令行时,我得到测试失败的信息,但是在WebStorm中我得到了这个信息
这是测试的代码
const chai = require('chai');
const chaiHttp = require('chai-http');
const request = require('supertest');
const app = require('../app');
const { expect, } = chai;
chai.use(chaiHttp);
const generateUser = (email, password, passwordRepeat) => ({ email, password, passwordRepeat, });
describe('Users', () => {
describe('POST /users/register', () => {
it('should get an error saying "Password is invalid"', () => {
request(app)
.post('/users/register')
.send(generateUser('test@test.tes', 'invalid', 'invalid'))
.expect(200)
.end((err, res) => {
expect(JSON.stringify(res.body)).to.equal(JSON.stringify({
errors: [
'Password is invalid',
],
ok: false,
}));
});
});
it('should get an error saying "Passwords do not match"', () => {
request(app)
.post('/users/register')
.send(generateUser('test@test.tes', 'zaq1@WSX', 'invalid2'))
.end((err, res) => {
expect(JSON.stringify(res.body)).to.equal(JSON.stringify({
errors: [
'Passwords do not match',
],
ok: true,
}));
});
});
it('should get an error saying "Email is invalid"', () => {
request(app)
.post('/users/register')
.send(generateUser('test@test.tessada', 'zaq1@WSX', 'zaq1@WSX'))
.expect(200)
.end((err, res) => {
expect(JSON.stringify(res.body)).to.equal(JSON.stringify({
errors: [
'Email is invalid',
],
ok: false,
}));
});
});
});
});
有趣的是,只有在我对describe块运行测试后,这种情况才会发生。一次可以进行多个测试。如果我只运行一个测试,则会收到错误消息。我该如何解决?
答案 0 :(得分:2)
这是一个异步测试,您应该使用Mocha提供的done
回调。否则,您的it()
测试将在请求断言运行之前成功完成,这意味着无需测试。
超级测试suggests可以像这样使用它:
// add done parameter below
it('should get an error saying "Password is invalid"', (done) => {
request(app)
.post('/users/register')
.send(generateUser('test@test.tes', 'invalid', 'invalid'))
.expect(200)
.end((err, res) => {
expect(JSON.stringify(res.body)).to.equal(JSON.stringify({
errors: [
'Password is invalid',
],
ok: false,
}));
// call done() when test/assertions finished
done();
});
});
当然,您应该对所有异步测试都这样做。