Hea*_*ath 5 javascript reactjs jestjs enzyme
使用 Jest 和 Enzyme,如何测试 this.props.functionToTest 是否已运行?
class TestComponent extends Component {
static propTypes = {
functionToTest: PropTypes.func
}
componentDidMount() {
this.props.functionToTest()
}
}
Run Code Online (Sandbox Code Playgroud)
在 Jest 中,我尝试创建 mockProps 并在安装组件时将它们传入。
let props = {
functionToTest = jest.fn(() => {});
}
beforeEach(() => {
const wrapper = mount(<TestComponent {...props} />
}
Run Code Online (Sandbox Code Playgroud)
componentDidMount 函数中的 console.log 将 functionToTest 显示为未定义。显然,在 mount 期间传入 props 是行不通的。
问题 1:如何传入将在 componentDidMount 函数中显示的模拟道具?
问题 2:一旦该函数可用,我如何获得对该函数的访问权限,以便我可以使用 spyOn 或类似的东西来测试该函数是否已运行?
我不知道你的确切设置,但我会这样做:
jest.fn()像你一样模拟功能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();
});
Run Code Online (Sandbox Code Playgroud)
问题最终是 TestComponent 仅在 Redux 包装器中导出。在类级别添加导出并在 Jest 测试导入中对其进行解构,以及上面发布的 Henrick 解决方案修复了该问题。
| 归档时间: |
|
| 查看次数: |
9891 次 |
| 最近记录: |