[英]Enzyme/Jest: How to test if mocked function has been called
I'm trying to test for the call of fetch()
inside of my changeIt()
function using jest/enzyme. 我正在尝试使用玩笑/酶测试在
changeIt()
函数内部对fetch()
的调用。 But obviously I'm doing something wrong: 但显然我在做错事:
example.js 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 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
})
You need to properly mock the node-fetch
module. 您需要正确模拟
node-fetch
模块。 Because it is in node_modules
, you need to put node-fetch
inside a __mocks__
folder on the same level as node_modules
like: 由于它位于
node_modules
,因此您需要将node-fetch
放在__mocks__
文件夹中,位于与node_modules
相同级别的node_modules
例如:
├── node_modules/
│ ├── node-fetch/
├── __mocks__/
│ ├── node-fetch.js
Inside node-fetch.js
put: 在
node-fetch.js
内部放:
export default jest.fn();
Finally import fetch
in your test file and mock it like this: 最后,将
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
})
Read more about mocking node_modules
packages in jest here. 在这里阅读更多关于嘲笑
node_modules
软件包的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.