ecmascript-6 - 如何用 Jest 取消模拟单个实例方法

标签 ecmascript-6 mocking jestjs es6-class

来自 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/

相关文章:

javascript - 如何使用 Jest 检查对象属性是否匹配?

vue.js - 使用 Jest 测试时未定义全局节点配置变量

javascript - 映射对象然后在页面上设置innerHTML会导致项目之间出现逗号

javascript - 'Object.assign' 在更深层次上改变状态

javascript - 检查数组中的任何对象是否包含另一个数组中列出的属性

asp.net-mvc - asp.net mvc如何正确测试 Controller

XDocument.Load() 和 XDocument.Save() 的测试方法

java:如何模拟 Calendar.getInstance()?

javascript - useFakeTimers 和异步回调

javascript - 按值或值组比较数组