使用 expect.any() 和 supertest 检查响应主体

Using expect.any() with supertest to check response body

我正在尝试使用 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 期望 api.

您可以使用 expect.objectContaining(object).

matches any received object that recursively matches the expected properties. That is, the expected object is a subset of the received object. Therefore, it matches a received object which contains properties that are present in the expected object.

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/Whosebug/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/Whosebug/47865190