node.js - 使用 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();
});
});
});
});
解决方案
我觉得这是因为你用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();
});
});
希望它有效
推荐阅读
- java - JsonobjectRequest 凌空库不工作
- java - Spring Data JPA 规范:过滤复杂数据
- matplotlib - 如何更改此混淆矩阵中的字体大小?
- xml - XPath 逻辑表达式
- javascript - Javascript 函数 .filter() 在 Iphone 上不起作用?
- python - 我想将 AUTH_USER_MODEL 定位到子目录中的自定义用户模型
- makefile - 我该如何解决这个问题“... .so: undefined reference to '...”
- android - 当第二个活动方向改变时 registerForActivityResult 不起作用
- coldfusion - 在 Coldfusion 2021 中使用 cfx_captcha 创建验证码时面临的问题
- postgresql - 将 PostgreSQL 数据库保存到外部硬盘