reactjs - 如何监视从另一个模块的另一个方法返回的方法
问题描述
我的项目中有 3 个文件 - a.js、utils.js、a.unit.spec.js。如何从 a.js 模拟 Jest (myFunc) 中的方法,该方法是 utils.js 中方法(帮助程序)的返回值(这是第三方库)?我收到此错误 -
无法窥探 myFunc 属性,因为它不是函数;给定的未定义
一个.js
import {helper} from 'utils.js'
export const myFunc = helper();
export const getData = () => {
return myFunc()
.then(...)
}
util.js(第三方库)
export const helper = (promiseFunc, time) => (...args) => (
Promise.race([
promiseFunc(...args),
new Promise((_, reject) =>
setTimeout(() => {...}, time)
),
])
);
a.unit.spec.js
import * as a from './a';
describe('getData', () => {
it('myFunc is called', () => {
const myFuncMock = jest.spyOn(a, 'myFunc');
a.getData().then(() => {})
expect(myFuncMock).toHaveBeenCalled();
})
})
解决方案
这是完成的演示:
a.ts
:
import { helper } from './utils';
export const myFunc = helper(async () => null, 1000);
export const getData = () => {
return myFunc().then(console.log);
};
utils.ts
:
export const helper = (promiseFunc, time) => (...args) =>
Promise.race([promiseFunc(...args), new Promise((_, reject) => null)]);
a.spec.ts
:
import * as a from './a';
describe('getData', () => {
it('myFunc is called', async () => {
const logSpy = jest.spyOn(console, 'log');
const myFuncMock = jest.spyOn(a, 'myFunc').mockResolvedValueOnce('mocked data');
await a.getData();
expect(myFuncMock).toHaveBeenCalled();
expect(logSpy).toBeCalledWith('mocked data');
});
});
单元测试结果:
PASS src/stackoverflow/58530865/a.spec.ts (5.431s)
getData
✓ myFunc is called (42ms)
console.log node_modules/jest-mock/build/index.js:860
mocked data
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 8.912s, estimated 17s
推荐阅读
- testing - Mockito - 是否可以深度模拟 void 方法调用以不做任何事情?
- python - 将 16 位 PCM 数据转换为 numpy 振幅数组
- c# - 将本机 dll (Gmsh4-7.dll) 添加到 dotnet 框架项目
- sql - SQL Subselect 在一行中计算
- html - 如何将页面从一个应用程序链接到另一个应用程序
- amazon-web-services - 仅允许用户为他创建/拥有的资源创建其他用户和策略
- java - 使用 JPA 会产生 SQL 语法错误
- javascript - NgBootstrap Typehead,如何获取无效字符串的“No Result found”消息
- mysql - SQL查询从科目表中选择已修完所有科目的学生
- sas - 为什么我收到 SAS ERROR 22-322 语法错误