如何用玩笑取消模拟单个实例方法 [英] how to unmock a single instance method with jest

查看:37
本文介绍了如何用玩笑取消模拟单个实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

coming from rspec, i am having trouble understanding mocking with jest. the approach i am trying for, is to automock a class's constructor and all of it's functions, and then unmock them one by one to test only that one function. the only documentation i can find on it, is with using 2 classes, mocking 1 class, and then testing that those functions are called from the other unmocked class.

下面是我正在尝试做的事情的一个基本的、人为的想法.有人可以指导我如何做这件事吗?

below is a basic, contrived idea of what i am trying to do. can someone direct me to the jest-way of doing this?

foo.js

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

foo_test.js

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

这篇关于如何用玩笑取消模拟单个实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆