如何在 Jest 中测试 Express 中间件的“验证”

How to test `verify` of an express middleware in Jest

我有一个 returns 中间件的函数:

const jsonParser = () => {
  return express.json({
    limit: '5mb',
    verify: (req, res, buf) => {
      // If the incoming request is a stripe event,
      if (req.headers['some-header']) {
        httpContext.set('raw-body', buf.toString());
      }
    },
  });
};

我想测试当 some-header header 存在时 httpContext.set 确实被调用。

我的测试:

describe('jsonParser middleware', () => {
  it('sets the http context', async () => {
    const req = {
      headers: {
        'some-header': 'some-sig',
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        some: 'thing',
      }),
    };

    const res = {};
    const middleware = jsonParser();

    middleware(req, res, () => {});

    expect(httpContext.set).toHaveBeenCalled();
  });
});

我不知道如何将测试 运行 函数传递给 verify。 Express 文档声明内容类型应该是 json,但仅此而已。非常感谢任何能为我指出正确方向的人。

谢谢。

如评论中所述,我想为您提供一个测试 header 和 jsonwebtoken 的集成测试示例。我也在使用 express 框架,但我用 JS 编写代码。

这是在我建立的论坛中创建论坛帖子的测试。中间件正在检查用户的令牌,因此这种情况可能与您的类似。

const request = require('supertest');

test('create authorized 201', async () => {
  const forumCountBefore = await ForumPost.countDocuments();
  const response = await request(app)
    .post('/api/forumPosts')
    .set({
      Authorization: `Bearer ${forumUserOne.tokens[0].token}`,
      userData: {
        userId: forumUserOneId,
        email: 'forum@controller.com',
        username: 'forum',
      },
    })
    .send(forumPost)
    .expect(201);
  expect(response.body.message).toBe('created forumPost');

  const forumCountAfter = await ForumPost.countDocuments();
  expect(forumCountBefore + 1).toBe(forumCountAfter);
});

我正在使用 mongoDB 这就是为什么我使用 ForumPost.countDocuments 来计算数据库中的条目数量的原因。

如您在测试中所见,我使用 supertest(作为请求导入)发送 http 调用。在 set 块中,我设置了授权令牌。这会导致在集成测试中执行中间件。

只有当中间件代码正确执行时测试才能通过,因此它应该覆盖您的中间件代码。