use*_*079 13 mocking reactjs jestjs enzyme
我有一个功能组件,我想用模拟功能测试它(简化演示)
const remove = () => {
... do something
}
const removeButton = (props) => (
<Button onClick={() => remove()}>
Remove
</Button>
);
Run Code Online (Sandbox Code Playgroud)
我试过这个测试用例
it('test remove button', () => {
const test = shallow(<removeButton/>)
const mockFunction = jest.fn()
test.instance().remove = mockFunction
test.find('Button').simulate('click')
expect(mockFunction).toHaveBeenCalled()
})
Run Code Online (Sandbox Code Playgroud)
.instance().remove 无法模拟该函数,因为它超出了范围。我将如何模拟 remove 函数?
您应该将remove
函数作为 prop 传递,而不是仅仅定义模块私有的相邻变量。
const removeButton = (props) => (
<Button onClick={() => props.remove()}>
Remove
</Button>
)
// test file
it('test remove button', () => {
const mockFunction = jest.fn()
const test = shallow(<RemoveButton remove={mockFunction} />)
test.find('Button').simulate('click')
expect(mockFunction).toHaveBeenCalled()
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16514 次 |
最近记录: |