我正在测试一个创建用户的 api。该 API 不允许创建具有相同登录值的用户。所以我编写了以下测试:
const app = require('../config/express'); //exports a configured express app
const request = require('supertest');
const {populateUsers} = require('../seeders/users.seed');
beforeEach(populateUsers);//drop and populate database with some seeders
describe('POST /v1/users', () => {
it('#Post a new user - 201 status code', (done) => {
request(app)
.post('/v1/users')
.send({
login:'user-teste-01',
password: 'pass01'
}).expect(201, done);
});
it('#Post repeated login - 400 status code', (done) => {
request(app)
.post('/v1/users')
.send({
login:'user-teste-01',
password: 'pass01'
}).expect(400, done);
});
});
第一个测试有效,但第二个测试返回以下错误:
Error: expected 400 "Bad Request", got 201 "Created"
我手动进行了测试,API 工作正常(返回 400 状态代码)。
这次测试我在哪里犯了错误?
最佳答案
这是因为您有 beforeEach
重置了数据库。此 Hook 将在每个测试中执行,因此在您的 400 状态代码
中,您不再拥有用户 user-teste-01
,因为它已被 beforeEach< 重置
。
对此有一些解决方案:
#1 使用种子中存在的登录名和密码
it('#Post repeated login - 400 status code', (done) => {
request(app)
.post('/v1/users')
.send({
login: 'user-exist-in-seed',
password: 'pass01'
}).expect(400, done);
});
#2 在运行场景之前再次创建用户
context('when user is already exist', function() {
beforeEach(function() {
// create a user `user-teste-01`
// use beforeEach so it will be executed after seeding
})
it('#Post repeated login - 400 status code', (done) => {
request(app)
.post('/v1/users')
.send({
login: 'user-teste-01',
password: 'pass01'
}).expect(400, done);
});
});
3 使用 before 而不是 beforeEach 进行播种
它将在所有测试之前运行一次
before(populateUsers);//drop and populate database with some seeders
关于node.js - Supertest无法测试重复的post请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52322530/