使用 Jest 和 Enzyme,我如何测试 this.props.functionToTest 是否运行?
class TestComponent extends Component {
static propTypes = {
functionToTest: PropTypes.func
}
componentDidMount() {
this.props.functionToTest()
}
}
在 Jest 中,我尝试创建 mockProps 并在挂载组件时将它们传入。
let props = {
functionToTest = jest.fn(() => {});
}
beforeEach(() => {
const wrapper = mount(<TestComponent {...props} />
}
componentDidMount 函数中的 console.log 显示 functionToTest 未定义。显然在挂载过程中传递 Prop 是行不通的。
问题 1:如何传入将在 componentDidMount 函数中显示的模拟 Prop ?
问题 2:一旦该函数可用,我如何获得对该函数的访问权限,以便我可以使用 spyOn 或类似的东西来测试该函数是否运行?
最佳答案
我不知道您的确切设置,但我会这样做:
- 像你一样用
jest.fn()
模拟函数 - 将 mock 传递给正在挂载的组件(就像你所做的那样)
- 检查它是否使用
expect(...).toBeCalled()
或.toHaveBeenCalled()
运行(不同 Jest 版本之间有所不同)
.
let props = {
functionToTest: jest.fn() // You don't need to define the implementation if it's empty
};
beforeEach(() => {
const wrapper = mount(<TestComponent {...props} />
}
// In the test code:
it('does something', () => {
expect(props.functionToTest).toBeCalled();
// OR... depending on your version of Jest
expect(props.functionToTest).toHaveBeenCalled();
});
关于javascript - 使用 Jest 和 Enzyme,如何测试通过 props 传入的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53729825/