js如何测试另一个函数内部被调用的函数

js如何测试另一个函数内部被调用的函数

本文介绍了Jest.js如何测试另一个函数内部被调用的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于测试,我使用jest和react-test-renderer.测试应该很简单,但是我很难找到合适的例子.我试图做类似的事情(通常我将功能保存在单独的文件中):

For testing I use jest and react-test-renderer. It should be simple to test, however I have a hard time finding the proper example. I have tried to do something like that (in general I keep the functions in separate files):

utils.js

export const childFunction = () => 'something';
const parentFunction = () => childFunction();
export default parentFunction;

utils.test.js

utils.test.js

import parentFunction from './utils.js';


it('childFunction should be called', () => {
 const childFunction = jest.fn();
 parentFunction();
 expect(childFunction).toBeCalled();
})

片段 const childFunction = jest.fn(); 绝对不起作用.调用时,parentFunction的主体仅关心其自身的作用域.但是,如果我导入childFunction并执行 jest.mock(childFunction),它也将不起作用,因为jest.mock需要一个字符串,一个模块的url,而不是函数本身.

The fragment const childFunction = jest.fn(); definitely won't work. While calling, parentFunction's body cares only about its own scope. But it also won't work if I import childFunction and do jest.mock(childFunction), because jest.mock needs a string, a url to a module, and not the function itself.

上面的示例不起作用,我正在寻找替代方法.但是,在使用ShallowRenderer渲染组件后,此方法有效.而且我想通过嵌套在另一个函数中的函数来实现类似的行为.

The example above doesn't work and I'm searching for an alternative. However this works after rendering the component with ShallowRenderer. And I'd like to achieve a similar behaviour with a function nested inside another function.

class Component extends React.Component {
 componentDidMount() {parentFunction()}
 render() {...}
}

const renderer = new ShallowRenderer();
describe("testing parentFunction", () => {
  renderer.render(<Component/>);
  it("parentFunction should be called", () => {
    expect(parentFunction).toBeCalled();
  });
});

推荐答案

如果未将函数作为对象方法调用,则无法监视函数调用.

There's no way to spy on function call if a function isn't called as object method.

此答案中所述,由于ES模块的工作方式,只有在以下情况下才可能监视或模拟函数:它是从一个模块导出的,并在另一个模块中使用.这样,就可以在模块*对象上对其进行监视,或者使用jest.mock对其进行模拟.

As explained in this answer, due to how ES modules work, it's possible to spy or mock a function only if it was exported from a module and is used in another module. This way it can be spied on module * object, or be mocked with jest.mock.

如果不是这种情况,则应进行间接测试:

If this isn't the case, it should be tested indirectly:

expect(childFunction()).toBe('something');
expect(parentFunction()).toBe('something');

这篇关于Jest.js如何测试另一个函数内部被调用的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:01