Jestjs如何测试在另一个函数内部被调用的函数。

12 浏览
0 Comments

Jestjs如何测试在另一个函数内部被调用的函数。

在测试中,我使用jest和react-test-renderer。测试应该很简单,然而我很难找到合适的示例。我尝试做了类似这样的事情(通常情况下,我将函数放在单独的文件中):

utils.js

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

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,而不是函数本身。

上述示例不起作用,我正在寻找替代方案。然而,在使用ShallowRenderer渲染组件后,这个方法可以工作。我希望实现类似的行为,一个函数嵌套在另一个函数中。

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

0