如何用 jest 取消模拟单个实例方法

问题描述 投票:0回答:5

来自 rspec,我无法理解用玩笑进行的嘲笑。我正在尝试的方法是自动模拟一个类的构造函数及其所有函数,然后一一取消模拟它们以仅测试该一个函数。我能找到的唯一文档是使用 2 个类,模拟 1 个类,然后测试这些函数是否是从另一个未模拟的类中调用的。

下面是我想做的事情的一个基本的、人为的想法。有人可以指导我这样做的笑话吗?

foo.js

class Foo
  constructor: ->
    this.bar()
    this.baz()
  bar: ->
    return 'bar'
  baz: ->
    return 'baz'

foo_test.js

// require the class
Foo = require('foo')

// mock entire Foo class methods
jest.mock('foo')

// unmock just the bar method
jest.unmock(Foo::bar)

// or by
Foo::bar.mockRestore()

// and should now be able to call
foo = new Foo
foo.bar() // 'bar'
foo.baz() // undefined (still mocked)

// i even tried unmocking the instance
foo = new Foo
jest.unmock(foo.bar)
foo.bar.mockRestore()
ecmascript-6 mocking jestjs es6-class
5个回答
16
投票

mockFn.mockRestore()
为我工作
[email protected]
:

// Create a spy with a mock
const consoleInfoSpy = jest.spyOn(console, 'info').mockImplementation(() => {})

// Run test or whatever code which uses console.info
console.info('This bypasses the real console.info')

// Restore original console.info
consoleInfoSpy.mockRestore()

11
投票

这并不严格适用于OP,但寻求答案的人可能会在这里结束。您可以像这样模拟一个模块,除了某些部分之外的所有测试

模拟/saladMaker.js

// Let Jest create the mock.
const saladMaker = jest.genMockFromModule('../saladMaker');

// Get the unmocked chop method.
const {chop} = jest.requireActual('../saladMaker');

// Patch it in.
saladMaker.chop = chop;

module.exports = saladMaker;

关键部分是使用

requireActual
来获取未模拟的模块。

绕过模块模拟


4
投票

在 Jest 中模拟后无法获取原始模块。

jest.mock
的作用是将模块替换为您的模拟。

所以即使你写:

Foo = require('foo')
jest.mock('foo')

Jest 会将

jest.mock('foo')
调用提升到调用堆栈的顶部,因此这是测试开始时发生的第一件事。这也会影响您导入和导入的所有其他模块
foo.js

您可以尝试使用

spyOn
来监视对象的函数,也应该与类一起使用,但我不太确定。


1
投票

我尝试了很多东西,但最终对我有用的是(使用 Create React App):

setupTests.ts

jest.mock("./services/translations/translationsService", () => ({
  __esModule: true,
  default: {
    initDict: (): void => undefined,
    translate: (key: Phrases): string => key,
  },
  t: (key: Phrases): string => key,
}));

它模拟所有测试的模块。为了解锁单个测试套件,我做了:

jest.mock("../../../services/translations/translationsService", () =>
  jest.requireActual("../../../services/translations/translationsService")
);

describe(() => { /* test suite goes here and uses real implementation */ });

0
投票

开玩笑@27.4.7

const mockChildComponent = jest.mock('../../../src/components/common/childComponent', () => ({
  __esModule: true,
  default: (props: Prop) => (
    <div data-test-id="stub-chart-panel">
      {props.label}
    </div>
  ),
}));

test('mock child', async () => {
  const wrapper = mount(
      <ParentComponent />
  );
  expect(....);
});

mockChildComponent.restoreAllMocks();

test('default child component ', async () => {
  const wrapper = mount(
      <ParentComponent />
  );
  expect(....);
});
© www.soinside.com 2019 - 2024. All rights reserved.