我正在尝试使用 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
模块。因为是在node_modules
里面,所以需要把node-fetch
放到__mocks__
文件夹里面,和node_modules
同级> 喜欢:
├── node_modules/
│ ├── node-fetch/
├── __mocks__/
│ ├── node-fetch.js
在 node-fetch.js
里面放:
export default jest.fn();
最后在您的测试文件中导入 fetch
并像这样模拟它:
import Example from './Bla';
import { shallow } from 'enzyme';
import React from 'react';
import fetch from 'node-fetch';
/**
* Important! Import the mocked function.
* Start the mocking with jest.mock('node-fetch').
* Stop the mocking with jest.unmock('node-fetch').
*/
jest.mock('node-fetch');
test('should call fetch()', () => {
const id = 1
const value = 50
const wrapper = shallow(<Example />)
wrapper.instance().changeIt(id, value)
expect(fetch).toHaveBeenCalled() // now it works
})
关于javascript - enzyme /Jest : How to test if mocked function has been called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52903643/