【问题标题】:Why does jest not mock this module?为什么 jest 不模拟这个模块?
【发布时间】:2020-02-29 16:27:26
【问题描述】:

我有一个应该调用本地提取包装器的模块。为了检查 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()
  })
})

但是当我运行它时,它会失败:

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

Expected mock function to have been called.

那么为什么不调用模拟呢?

【问题讨论】:

    标签: javascript mocking jestjs


    【解决方案1】:

    问题是所有jest.mock 语句都被提升到代码块的顶部。因此,即使您将其写入测试中间,它也会作为测试的第一条语句运行,并且无法获得特定的返回值。那么如何解决这个问题呢?首先将 mock 语句放在 import 语句之后,以明确在测试中没有发生 mock。然后在您的测试中导入模块。所以这将是模拟语句中jest.fn() 的结果。由于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()
      })
    })
    

    【讨论】:

    • 但是文档说:Note: When using babel-jest, calls to mock will automatically be hoisted to the top of the code block. Use doMock if you want to explicitly avoid this behavior. 它应该保留在同一块右侧,而不是文件的顶部?
    • 对不起,我在这一点上有点错误。即便如此,在你声明const mockFetch = jest.fn()之前。
    • 你知道我为什么不开玩笑吗const wantToAssertSomeStuff = jest.mock('../fetch', () => jest.fn())
    • 除了上面的好答案之外,我发现这篇关于模拟部分的文章 jestjs.io/docs/mock-functions#mocking-partials 非常有帮助
    猜你喜欢
    • 2019-09-02
    • 2019-08-17
    • 1970-01-01
    • 2020-06-10
    • 2021-02-04
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多