首页 > 解决方案 > 如何监视从另一个模块的另一个方法返回的方法

问题描述

我的项目中有 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();
    })
})

标签: reactjsjestjs

解决方案


这是完成的演示:

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

推荐阅读