监视在 Jest 中调用另一个函数的导入函数 [英] Spying on an imported function that calls another function in Jest

查看:30
本文介绍了监视在 Jest 中调用另一个函数的导入函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图监视另一个函数调用的函数,这两个函数都驻留在外部文件中并导入.

I'm trying to spy on a function that's called by another function, both of which reside in an external file and imported.

Funcs.spec.js:

Funcs.spec.js:

import * as Funcs from './Funcs'
describe('funcA', () => {
    it('calls funcB', () => {
        jest.spyOn(Funcs, 'funcB')
        Funcs.funcA()
        expect(Funcs.funcB).toHaveBeenCalled()
    }
}

Funcs.js:

export const funcA = () => {
    funcB()
}
export const funcB = () => {}

出于某种原因,在 Funcs.js 的范围内不尊重间谍.我可以做什么来监视 funcB 以便我知道 funcA 调用了它?

For some reason the spy is not respected in scope of Funcs.js. What can I do to spy on funcB so I know funcA has called it?

推荐答案

只能监视方法.如果 funcB 在同一个模块中像 funcB() 一样直接调用,则无法窥探它.

Only methods can be spied. There is no way to spy on funcB if it's called directly like funcB() within same module.

为了让导出的函数被监视或模拟,funcAfuncB 应该驻留在不同的模块中.

In order for exported function to be spied or mocked, funcA and funcB should reside in different modules.

这允许在 transpiled ES 模块中监视 funcB(模块对象在原生 ESM 中是只读的):

This allows to spy on funcB in transpiled ES module (module object is read-only in native ESM):

import { funcB } from './b';

export const funcA = () => {
    funcB()
}

由于模块导入是模块的表示,因此转换为:

Due to that module imports are representations of modules, this is transpiled to:

var _b = require('./b');

var funcA = exports.funcA = function funcA() {
    (0, _b.funcB)();
};

其中 funcB 方法绑定到 _b 模块对象,因此可以对其进行监视.

Where funcB method is tied to _b module object, so it's possible to spy on it.

这篇关于监视在 Jest 中调用另一个函数的导入函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆