簡體   English   中英

在jest.mock(moduleName,factory)工廠函數中模擬多個命名的導出

[英]Mocking multiple named exports in jest.mock(moduleName, factory) factory function

我在一個小項目中一直在使用Jest,但是在使用Jest模擬時遇到了麻煩。 我有一個實用程序文件,可導出命名的自定義錯誤構造函數。 我需要在測試文件中模擬這些功能。 我不想使用Jest文檔中顯示的手動模擬技術(即,將模擬文件放入__mocks__ ),而是想在測試文件中定義模擬。 我正在測試文件中嘗試以下操作:

const errorMock = () => {
  return {
    configNotFoundError: jest.fn(() => new Error()),
    invalidJSONError: () => jest.fn(() => new Error()),
  }
};

jest.mock('./error', errorMock);

const { configNotFoundError, invalidJSONError } = require('./error');

但是我收到以下錯誤:

babel-plugin-jest-hoist: The second argument of `jest.mock` 
must be an inline function.

有人可以幫助我了解我在做什么錯嗎?

最近,我在命名出口上遇到了類似的問題。 根據文檔jest.mock調用被提升到測試的頂部,並隨后在定義errorMock之前執行。 這些調用似乎已懸掛了功能。 嘗試:

function errorMock() {
  return {
    configNotFoundError: jest.fn(() => new Error()),
    invalidJSONError: () => jest.fn(() => new Error()),
  }
};

jest.mock('./error', errorMock);

const { configNotFoundError, invalidJSONError } = require('./error');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM