【问题标题】:Enzyme/Jest: How to test if mocked function has been calledEnzyme/Jest:如何测试是否调用了模拟函数
【发布时间】:2018-10-20 08:01:19
【问题描述】:

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

【问题讨论】:

标签: javascript reactjs unit-testing jestjs enzyme


【解决方案1】:

您需要正确模拟 node-fetch 模块。因为它在node_modules中,所以你需要将node-fetch放在与node_modules同级的__mocks__文件夹中,例如:

├── 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.

【讨论】:

  • 了解,它正在工作。那我就不需要jest.mock('node-fetch')
  • 我有点不清楚,我会编辑它。你仍然需要这样做,因为每次测试你都可以模拟/取消模拟。
猜你喜欢
  • 2020-06-22
  • 1970-01-01
  • 1970-01-01
  • 2017-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-02
相关资源
最近更新 更多