WebStorm 中通过断言的测试失败

Tests passing with assertion fails in WebStorm

我正在尝试 运行 使用 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,
          }));
        });
    });
  });
});

有趣的是,这只发生在我 运行 描述块上的测试中。所以一次进行多项测试。如果我 运行 只是一个测试,我会得到错误。我该如何解决?

这是一个异步测试,您应该使用 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();
        });
    });

当然,您应该为所有异步测试执行此操作。