我正在尝试使用玩笑/酶在fetch()
函数内部测试对changeIt()
的调用。
但显然我在做错事:
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
})
答案 0 :(得分:3)
您需要正确模拟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
})