使用带有supertest的expect.any()来检查响应主体

时间:2017-12-18 09:14:04

标签: unit-testing jestjs supertest

我正在尝试使用supertest来检查使用Jest的res.body,但以下代码段将始终失败

    request(app)
        .post('/auth/signup')
        .send(validEmailSample)
        .expect(200, {
            success: true,
            message: 'registration success',
            token: expect.any(String),
            user: expect.any(Object)
        }));

但是当我重写测试以在回调中检查正文时如下:

    test('valid userData + valid email will result in registration sucess(200)' +
        ', with message object.', (done) => {
            request(app)
                .post('/auth/signup')
                .send(validEmailSample)
                .expect(200)
                .end((err, res) => {
                    if (err) done(err);
                    expect(res.body.success).toEqual(true);
                    expect(res.body.message).toEqual('registration successful');
                    expect(res.body.token).toEqual(expect.any(String));
                    expect(res.body.user).toEqual(expect.any(Object));
                    expect.assertions(4);
                    done();
                });

测试将通过。

我确定它与expect.any()有关。正如Jest的文档所说,expect.any和expect.anything只能与expect().toEqualexpect().toHaveBeenCalledWith()一起使用 我想知道是否有更好的方法来使用expect.any在supertest的期望api。

1 个答案:

答案 0 :(得分:0)

这是一个解决方案:

app.js

const express = require("express");
const app = express();

app.post("/auth/signup", (req, res) => {
  const data = {
    success: true,
    message: "registration success",
    token: "123",
    user: {},
  };
  res.json(data);
});

module.exports = app;

app.test.js

const app = require('./app');
const request = require('supertest');

describe('47865190', () => {
  it('should pass', (done) => {
    expect.assertions(1);
    request(app)
      .post('/auth/signup')
      .expect(200)
      .end((err, res) => {
        if (err) return done(err);
        expect(res.body).toEqual(
          expect.objectContaining({
            success: true,
            message: 'registration success',
            token: expect.any(String),
            user: expect.any(Object),
          }),
        );
        done();
      });
  });
});

具有覆盖率报告的集成测试结果:

 PASS  src/stackoverflow/47865190/app.test.js (12.857s)
  47865190
    ✓ should pass (48ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 app.js   |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        14.319s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/47865190