我正在尝试使用 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,
}));
});
});
});
});
有趣的是,这只发生在我在描述 block 上运行测试时。因此一次进行多个测试。如果我只运行一项测试,我会得到错误。我该如何解决?
最佳答案
这是一个异步测试,您应该使用 done
Mocha 提供的回调.否则,您的 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();
});
});
当然,您应该为所有异步测试执行此操作。
关于javascript - 在 WebStorm 中通过断言的测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61386678/