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

标签 javascript reactjs unit-testing jestjs enzyme

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

相关文章:

javascript - jquery触发CSS3页面加载效果

javascript - Hook的规则 顶层在哪里

javascript - 在有状态和无状态组件中使用 Props

reactjs - 我什么时候应该使用快照测试?

c# - 为什么我的 Silverlight XAML 绑定(bind)单元测试失败?

javascript - 顶部固定导航栏中的链接无响应

javascript - 我想我了解异步、等待、 promise 和回调,但我对异步代码有疑问

javascript - Three.js - 全景应用到reactjs中

c# - 当代码验证它收到的类型时,如何使用模拟

javascript - 为什么我的悬停 CSS 被 jQuery 删除了?