node.js - 使用 jest 和 superagent 进行测试时如何模拟函数

标签 node.js express jestjs superagent

我遇到了一个问题,即在 API 调用的处理程序中使用的文件和函数无法被模拟。此调用是使用 superagent 模拟的。

这是测试代码

// users.itest.js
const request = require('superagent');
const get = async url => request
  .get(`${process.env.API_URL}${url}`);

describe('endpoint', () => {
it('GET', async () => {
  jest.mock('../token-store', () => ({
    getToken: jest.fn().mockReturnValue('token'),
  }));

  const { status, body } = await get('/api/users');
  expect(status).toEqual(200);
  expect(body).toHaveValidSchema(userSchema);
});

这是由“/api/users”端点调用的处理程序

const someHandler = async (req, res) => {
  const token = await tokenStore.getToken();

  res.send(token);
};

我尝试像所示那样 mock 它,但是,我找不到解决方案。 谢谢。

最佳答案

您应该在模块范围内使用 jest.mock(),而不是函数范围。

这是集成测试解决方案:

app.js:

const express = require('express');
const tokenStore = require('./token-store');

const app = express();

const someHandler = async (req, res) => {
  const token = await tokenStore.getToken();
  res.send(token);
};

app.get('/api/users', someHandler);

module.exports = app;

token-store.js:

async function getToken() {
  return 'real token';
}

module.exports = {
  getToken,
};

users.test.js:

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

const port = 3000;
process.env.API_URL = `http://localhost:${port}`;
const get = async (url) => request.get(`${process.env.API_URL}${url}`);

jest.mock('./token-store', () => ({
  getToken: jest.fn().mockReturnValue('token'),
}));

describe('endpoint', () => {
  let server;
  beforeAll((done) => {
    server = app.listen(port, () => {
      console.info(`HTTP server is listening on http://localhost:${server.address().port}`);
      done();
    });
  });

  afterAll((done) => {
    server.close(done);
  });

  it('GET', async () => {
    const { status, text } = await get('/api/users');
    expect(status).toEqual(200);
    expect(text).toBe('token');
  });
});

集成测试结果与覆盖率报告:

 PASS  src/stackoverflow/59426030/users.test.js (10.767s)
  endpoint
    ✓ GET (74ms)

  console.info src/stackoverflow/59426030/users.test.js:16
    HTTP server is listening on http://localhost:3000

----------|----------|----------|----------|----------|-------------------|
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:        12.254s

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

关于node.js - 使用 jest 和 superagent 进行测试时如何模拟函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59426030/

相关文章:

javascript - 尽管使用缓冲区调用,文件类型 npm 模块仍返回 null,我做错了什么?

javascript - 使用正则表达式和express-jsonschema来验证数组的内容

javascript - 根据环境变量阻止 JEST 运行

node.js - 请求 promise - 使用端口向服务器发送错误的请求

node.js - Mongoose 聚合 - 有条件查找(user1 或 user2)

node.js - 我可以在 Node 中同时拥有多少个计划作业

reactjs - 尝试使用 create-react-app 运行 typescript

javascript - Vue 测试 - '... .push is not a function'

javascript - 串行通信 - node.js - arduino 板没有应答

node.js - Object.create 在 NodeJS 中