node.js - 使用 jest 和 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);
};
我尝试像显示的那样模拟它,但是,我找不到解决方案。谢谢。
解决方案
您应该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
推荐阅读
- r - 在保留日期的同时在特定窗口内移动平均值,R
- java - 在我的 SpringBoot 项目中,当我将文件目录更改为 src/main/resources 时发生 FileNotFoundException
- android - 如何找到apk的正确MD5 Key Hash
- c++ - 如何为 C++ 14 /C ++17 设置 VS 代码
- hyperledger-fabric - 在超级账本中启动网络时遇到错误
- .net - Microsoft Visual Studio 2005 可用性
- sql - 使用内连接删除需要 40 多秒才能删除 500 行
- javascript - 从 node-fetch 返回一个值
- html - 上传,编辑和替换html和angular 4中的现有文件图像
- dart - Dart - 如何使用不同的主体进行多个 http.post 请求