酶/玩笑:如何测试是否调用了模拟功能

时间:2018-10-20 08:01:20

标签: javascript reactjs unit-testing jestjs enzyme

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

1 个答案:

答案 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
})

Read more about mocking node_modules packages in jest here.