Ecmascript 6 如何使用jest卸载单个实例方法

Ecmascript 6 如何使用jest卸载单个实例方法,ecmascript-6,mocking,jestjs,es6-class,Ecmascript 6,Mocking,Jestjs,Es6 Class,来自rspec,我很难理解开玩笑的嘲弄。我尝试的方法是,自动模拟一个类的构造函数和它的所有函数,然后逐个卸载它们,只测试一个函数。我能找到的唯一文档是使用2个类,模拟1个类,然后测试这些函数是否从另一个未经修改的类调用 下面是我试图做的一个基本的、人为的想法。有人能告诉我怎么做吗 foo.js class Foo constructor: -> this.bar() this.baz() bar: -> return 'bar' baz: ->

来自rspec,我很难理解开玩笑的嘲弄。我尝试的方法是,自动模拟一个类的构造函数和它的所有函数,然后逐个卸载它们,只测试一个函数。我能找到的唯一文档是使用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()

在开玩笑地模仿原始模块之后,不可能得到它。
jest.mock
所做的是用您的mock替换模块

所以即使你写:

Foo = require('foo')
jest.mock('foo')
Jest将把
Jest.mock('foo')
调用提升到调用堆栈的顶部,因此这是测试开始时发生的第一件事。这也会影响您导入和导入的所有其他模块
foo.js


您可以尝试使用监视对象的函数,也可以使用类,但我不太确定。

这并不严格适用于OP,但答案搜索者可能会在这里结束。除某些部分外,您可以模拟模块进行所有测试,例如

模仿/saldmaker.js

//让Jest创建模拟。
const saladMaker=jest.genMockFromModule('../saladMaker');
//获取未经修改的chop方法。
const{chop}=require.requireActual('../saldmaker');
//把它补上。
沙拉制作者。切块=切块;
module.exports=沙拉制造商;
关键部分是使用
requireActual
获取未经检查的模块

更新
require.requireActual
with
jest.requireActual

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

我尝试了很多东西,但最终对我有效的是(使用CreateReact应用程序):

设置测试

jest.mock(“./services/translations/translationsService”,()=>({
__艾斯莫杜勒:没错,
默认值:{
initDict:():void=>未定义,
翻译:(键:短语):string=>key,
},
t:(键:短语):string=>key,
}));
它模拟模块进行所有测试。为了卸载单个测试套件,我执行了以下操作:

jest.mock(“../../../services/translations/translationservice”,()=>
jest.requireActual(“../../../../services/translations/TranslationService”)
);
描述(()=>{/*测试套件在这里使用实际实现*/});

是的,我也一直在玩这个,但也有同样的问题。我也在尝试模拟构造函数,但似乎也无法理解这一点。不知何故,jest正在这样做,但是查看他们的源代码可能需要比只了解myselfjest更长的时间。genMockFromModule()已被弃用,因此我们可以使用jest.createMockFromModule()