Supertest无法测试重复的帖子请求 [英] Supertest fails to test repeated post request

查看:74
本文介绍了Supertest无法测试重复的帖子请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试创建用户的api. api不允许创建具有相同登录值的用户.所以我写了下面的测试:

I'm testing an api that creates users. The api does not allow the creation of users with the same login value. So I wrote the tests below:

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);
  });
});

firts测试有效,但是第二个测试返回以下错误:

The firts test works, but the second test returns the following error:

Error: expected 400 "Bad Request", got 201 "Created"

我手动进行了测试,并且api正常工作(返回了400个状态代码).

I did the tests manually and the api works correctly (returning 400 status code).

在此测试中我在哪里犯了错误?

Where did I make the mistake in this test?

推荐答案

这是因为您有beforeEach可以重置数据库.该挂钩将在每次测试中执行,因此在您的400 status code中,您不再拥有用户user-teste-01,因为它已被beforeEach重置.

it is because you have beforeEach that reset your database. This hook will be executed in every test so in your 400 status code, you no longer have user user-teste-01 because it has been reset by 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使用之前而不是之前每个进行播种

它将在所有测试之前运行一次

3 Use before instead of beforeEach for seeding

It will run once before all tests

before(populateUsers);//drop and populate database with some seeders

这篇关于Supertest无法测试重复的帖子请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆