来自 rspec,我无法理解开玩笑的 mock 。我正在尝试的方法是自动模拟一个类的构造函数及其所有函数,然后将它们一个一个地取消模拟以仅测试该函数。我能找到的唯一文档是使用 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()
最佳答案
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()
关于ecmascript-6 - 如何用 Jest 取消模拟单个实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54109708/