我试图使用mochachaisupertest运行一个基本测试。当我使用命令行时,我得到了测试失败的信息,但在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('[email protected]', '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('[email protected]', '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('[email protected]', 'zaq1@WSX', 'zaq1@WSX'))
.expect(200)
.end((err, res) => {
expect(JSON.stringify(res.body)).to.equal(JSON.stringify({
errors: [
'Email is invalid',
],
ok: false,
}));
});
});
});
});
有趣的是,这只发生在我在一个描述块上运行测试的时候。所以一次进行多个测试。如果我只运行一个测试,我就会得到这个错误。我怎样才能解决这个问题?
这是一个异步测试,你应该使用 done
回调 摩卡. 否则,你的 it()
测试在请求断言运行之前就成功完成了,这意味着,不需要测试任何东西。
超级测试 建议 这样来使用它。
// add done parameter below
it('should get an error saying "Password is invalid"', (done) => {
request(app)
.post('/users/register')
.send(generateUser('[email protected]', '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();
});
});
当然,你应该为所有的异步测试做这个。