我正在为使用 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();
});
});
});
});