小编Jel*_*fra的帖子

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

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

utils.js

export const childFunction = () => 'something';    
const parentFunction = () => childFunction();
export default parentFunction;
Run Code Online (Sandbox Code Playgroud)

utils.test.js

import parentFunction from './utils.js';


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

片段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(<Component/>);
  it("parentFunction should be called", () => {
    expect(parentFunction).toBeCalled();
  });
});
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs react-test-renderer

6
推荐指数
2
解决办法
6305
查看次数

标签 统计

javascript ×1

jestjs ×1

react-test-renderer ×1

reactjs ×1