Enzyme/Jest:如何测试是否调用了模拟函数

use*_*695 1 javascript unit-testing reactjs jestjs enzyme

我正在尝试使用 jest/enzyme测试fetch()我的changeIt()函数内部的调用。但显然我做错了什么:

例子.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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

例子.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
})
Run Code Online (Sandbox Code Playgroud)

axm*_*m__ 5

您需要正确模拟node-fetch模块。因为它在 中node_modules,所以您需要将其放入与以下相同级别node-fetch__mocks__文件夹中node_modules

??? node_modules/
?   ??? node-fetch/
??? __mocks__/
?   ??? node-fetch.js
Run Code Online (Sandbox Code Playgroud)

里面node-fetch.js放:

??? node_modules/
?   ??? node-fetch/
??? __mocks__/
?   ??? node-fetch.js
Run Code Online (Sandbox Code Playgroud)

最后导入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
})
Run Code Online (Sandbox Code Playgroud)

node_modules在这里阅读更多关于在玩笑中模拟包的信息。