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

Ale*_*ong 2 unit-testing supertest jestjs

我正在尝试使用 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),
  });
Run Code Online (Sandbox Code Playgroud)

但是当我重写测试以检查回调中的主体时,如下所示:

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();
    });
});
Run Code Online (Sandbox Code Playgroud)

测试将通过。

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

sli*_*wp2 7

您可以使用expect.objectContaining(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;
Run Code Online (Sandbox Code Playgroud)

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();
      });
  });
});
Run Code Online (Sandbox Code Playgroud)

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

 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
Run Code Online (Sandbox Code Playgroud)

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