我使用jest和react-test-renderer进行测试。测试应该很简单,但是我很难找到合适的示例。我尝试过类似这样的方式(一般将函数保留在单独的文件中):
utils.js
export const childFunction = () => 'something';
const parentFunction = () => childFunction();
export default parentFunction;
实用工具测试.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(<Component/>);
it("parentFunction should be called", () => {
expect(parentFunction).toBeCalled();
});
});