【发布时间】:2018-10-20 08:01:19
【问题描述】:
我正在尝试使用 jest/enzyme 在我的 changeIt() 函数中测试对 fetch() 的调用。
但显然我做错了什么:
example.js
import fetch from 'node-fetch'
export default class Example extends Component {
changeIt (id, value) {
fetch('http://localhost/set-status?id=' + id + '&value=' + value)
}
render () {
return (
<div>something </div>
)
}
}
example.test.js
jest.mock('node-fetch')
test('should call fetch()', () => {
const id = 1
const value = 50
const fetch = jest.fn() // <- This is wrong
const wrapper = shallow(<Example />)
wrapper.instance().changeIt(id, value)
expect(fetch).toHaveBeenCalled() // <- This is wrong
})
【问题讨论】:
-
你嘲笑过'node-fetch'吗?
-
@axm__ 是的,如测试代码所示
-
但是你在测试函数中创建了一个新的本地模拟函数,与节点获取无关。再看jestjs.io/docs/en/mock-functions.html#mocking-modules
标签: javascript reactjs unit-testing jestjs enzyme