来自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()
5条答案
按热度按时间kcrjzv8t1#
mockFn.mockRestore()
对我的jest@24.9.0
起作用:kuhbmx9i2#
这并不严格适用于OP,但答案寻求者可能会在这里结束。你可以像这样模拟一个模块,除了某些部分的 * 所有测试 *。
模拟/沙拉制作器.js
关键部分是使用
requireActual
获取未模拟的模块。bypassing module mocks
w8rqjzmb3#
在Jest中模拟后不可能得到原来的模块。
jest.mock
所做的是用你的模拟替换这个模块。所以连你也写:
Jest会将
jest.mock('foo')
调用提升到调用栈的顶部,所以这是测试开始时发生的第一件事。这也会影响您导入的和导入foo.js
的所有其他模块。你可以试着用
spyOn
来监视一个对象的函数,应该也能用类,但是我不太确定。ve7v8dk24#
我尝试了很多方法,但最终对我有效的是(使用Create React App):
setupTests.ts
它为所有测试模拟模块。为了为单个测试套件取消模拟,我做了:
bksxznpy5#
对于Jest@27.4.7