简体   繁体   English

为什么 jest 不嘲笑这个模块?

[英]Why does jest not mock this module?

I have a module that's supposed to call a local fetch wrapper.我有一个应该调用本地提取包装器的模块。 To check whether the get module calls the fetch wrapper correctly I'm mocking it and returning a spy like so:为了检查 get 模块是否正确调用了 fetch 包装器,我正在模拟它并返回一个像这样的间谍:

// get.js
import fetch from '../fetch'

const get = (endpoint, token) => {
  const headers = new Headers()

  if (token) {
    headers.append('Authorization', `Bearer ${token}`)
  }

  const init = {
    headers,
    method: 'GET'
  }

  return fetch(new Request(endpoint, init))
}

export default get
// get.test.js
import 'isomorphic-fetch'
import get from './get'

describe('get', () => {
  it('calls fetch with a request', () => {
    // I'm expecting this spy to be called by get
    const mockFetch = jest.fn()
    jest.mock('../fetch', () => jest.fn(mockFetch))

    get('endpoint', 'token')

    expect(mockFetch).toHaveBeenCalled()
  })
})

But when I run it jest fails with:但是当我运行它时开玩笑失败了:

expect(jest.fn()).toHaveBeenCalled()

Expected mock function to have been called.

So why isn't it calling the mock?那么为什么不调用模拟呢?

The problem is that all jest.mock statements are hoisted to the top of code block.问题是所有jest.mock语句都被提升到代码块的顶部。 So even if you write it into the middle of your test it will be run as the first statement of your test and there is no way to have a specific return value.因此,即使您将它写入测试的中间,它也会作为测试的第一条语句运行,并且无法获得特定的返回值。 So how to fix this?那么如何解决这个问题呢? First put the mock statement after your import statements to make clear that the mocking not happening in the test.首先将 mock 语句放在 import 语句之后,以明确测试中不会发生模拟。 Then import the module in your test.然后在测试中导入模块。 So this will be the result of the jest.fn() in your mock statement.所以这将是模拟语句中jest.fn()的结果。 As fetch is a spy now you can test on this that fetch was called.由于fetch是间谍,现在您可以对此进行测试,该fetch被调用。

import 'isomorphic-fetch'
import get from './get'
import fetch from '../fetch'
jest.mock('../fetch', () => jest.fn())

describe('get', () => {
  it('calls fetch with a request', () => {
    get('endpoint', 'token')
    expect(fetch).toHaveBeenCalled()
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM