首页 > 解决方案 > 使用 chai 的 API 单元测试给出错误的结果

问题描述

我正在为使用 nodejs 和 mongoose 的 API 编写单元测试。我正在使用 mocha、chai 和 chai-http 进行单元测试。

我正在测试一个创建客户的 POST 请求。第一个测试创建了一个客户,它通过了。最后一个测试将尝试创建一个客户,但由于电子邮件已经存在,所以应该会失败,但由于请求会创建一个新客户,所以会失败。

我尝试使用邮递员手动执行请求,它给出了正确的行为。

以下是测试:

describe('Customer', () => {

//Before each test we empty the database
beforeEach((done) => {
    Customer.remove({}, (err) => {
        done();
    });
});

// Creating Customer test
describe('POST Account - Creating customer account', () => {

    it('creating a user with correct arguments', (done) => {

        // defining the body
        var body = {
            first_name : "Abdulrahman",
            last_name : "Alfayad",
            email: "test@test.com",
            password: "123"
        };

        chai.request(server)
        .post('/api/customer/account')
        .send(body).end((err, res) => {
            res.body.should.have.property('status').and.is.equal('success');
            res.body.should.have.property('message').and.is.equal('customer was created');
            done();
        });
    });

    it('creating a user with incorrect arguments', (done) => {

        // defining the body
        var body = {
            first_name: "Abdulrahman",
            email: "test@test.com",
        };

        chai.request(server)
            .post('/api/customer/account')
            .send(body).end((err, res) => {
                res.body.should.have.property('status').and.is.equal('failure');
                res.body.should.have.property('message').and.is.equal('no arguments were passed');
                done();
            });
    });

    it('creating a user with an already existing email in the DB', (done) => {

        // defining the body
        var body = {
            first_name: "Abdulrahman",
            last_name: "Alfayad",
            email: "test@test.com",
            password: "123"
        };

        chai.request(server)
            .post('/api/customer/account')
            .send(body).end((err, res) => {
                res.body.should.have.property('status').and.is.equal('failure');
                res.body.should.have.property('message').and.is.equal('email already exist');
                done();
            });
    });

});

});

标签: node.jsmongoosemocha.jschaichai-http

解决方案


我觉得这是因为你用beforeEach清空了客户数据库。beforeEach钩子将在每次测试之前执行,因此当您运行电子邮件场景测试时,您的数据库实际上是空的。

解决它的最简单方法是在现有电子邮件场景之前再次创建新客户,例如:

it('creating a user with an already existing email in the DB', (done) => {

  // NOTE: Create a user with email "test@test.com"

  // defining the body
  var body = {
    first_name: "Abdulrahman",
    last_name: "Alfayad",
    email: "test@test.com",
    password: "123"
  };

  chai.request(server)
    .post('/api/customer/account')
    .send(body).end((err, res) => {
      res.body.should.have.property('status').and.is.equal('failure');
      res.body.should.have.property('message').and.is.equal('email already exist');
      done();
    });
});

希望它有效


推荐阅读