我正在尝试使用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('[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,
}));
});
});
});
});
有趣的是,只有在我对describe块运行测试后,才会发生这种情况。一次可以进行多个测试。如果我只运行一个测试,则会收到错误消息。我该如何解决?
这是异步测试,您应该使用done
提供的Mocha回调。
Supertest建议像这样使用它:
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,
}));
done();
});
});