gpt4 book ai didi

javascript - enzyme /Jest : How to test if mocked function has been called

转载 作者:行者123 更新时间:2023-11-30 09:19:12 24 4
gpt4 key购买 nike

我正在尝试使用 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
})

Read more about mocking node_modules packages in jest here.

关于javascript - enzyme /Jest : How to test if mocked function has been called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52903643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com