如何使用jest取消模拟单示例方法

h43kikqp  于 2022-12-08  发布在  Jest
关注(0)|答案(5)|浏览(179)

来自rspec,我有困难理解用jest模拟。我尝试的方法是,自动锁定一个类的构造函数和它的所有函数,然后一个接一个地解除模拟,只测试一个函数。我能找到的唯一文档是,使用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()
kcrjzv8t

kcrjzv8t1#

mockFn.mockRestore()对我的jest@24.9.0起作用:

// 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()
kuhbmx9i

kuhbmx9i2#

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

模拟/沙拉制作器.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获取未模拟的模块。
bypassing module mocks

w8rqjzmb

w8rqjzmb3#

在Jest中模拟后不可能得到原来的模块。jest.mock所做的是用你的模拟替换这个模块。
所以连你也写:

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

Jest会将jest.mock('foo')调用提升到调用栈的顶部,所以这是测试开始时发生的第一件事。这也会影响您导入的和导入foo.js的所有其他模块。
你可以试着用spyOn来监视一个对象的函数,应该也能用类,但是我不太确定。

ve7v8dk2

ve7v8dk24#

我尝试了很多方法,但最终对我有效的是(使用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 */ });
bksxznpy

bksxznpy5#

对于Jest@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(....);
});

相关问题