监视在Jest中调用另一个函数的导入函数

监视在Jest中调用另一个函数的导入函数

本文介绍了监视在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.

这可以监视在编译的 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中调用另一个函数的导入函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:01