Модульный тест API с использованием chai дает неверный результат - PullRequest
0 голосов
/ 22 сентября 2018

Я пишу юнит-тест для моего API, который использует nodejs и mongoose.Я использую 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();
            });
    });

});

});

1 Ответ

0 голосов
/ 22 сентября 2018

Мне кажется, это потому, что вы используете 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();
    });
});

Надеюсь, что это работает

...