简体   繁体   English

在 ts-jest 中恢复导入的 class function 的模拟

[英]restore mock of imported class function in ts-jest

Issue问题

I am mocking a function (only one) which is imported from another class which is being called inside the main class.我是 mocking 一个 function(只有一个),它是从另一个 class 导入的,它在主 ZA2F21ED4F8EBC21CBB49 中被调用I am able to mock the function and return the values which I provide.我能够模拟 function 并返回我提供的值。 But I am not able to restore the mocked function back to normal for the subsequent tests.但是我无法将模拟的 function 恢复正常以进行后续测试。

Any help would be appreciated!任何帮助,将不胜感激!

Framework Using: jest + ts-jest框架使用:jest + ts-jest

Code代码

~main.ts ~main.ts

import {SubClass} from './subclass.ts'
export class MainClass {
 let sub: SubClass = new SubClass()

public async Car(){
  let start = await sub.key();
  return start
}

}

~sub.ts ~sub.ts

export class SubClass{ 

public async key(){
  return "you can start the car"
}
}

main.test.ts main.test.ts

import {SubClass} from './subclass.ts'
import {MainClass} from './mainclass.ts'
import {mocked} from 'ts-jest/utils'

jest.mock(./subclass.ts)

let main = new MainClass()
let sub = new SubClass()
let mockedFn = mocked(sub,true)

mockedFn.key = jest.fn().mockImplementation(() => console.log('mocking succesfull'))

afterEach(()=>{
mockedFn.key.mockRestore() // tried mockClear(), mockReset()
}

it('test for main func mocked result',async ()=>{
 const result = await main.car()
 expect(result).toEqual("mocking succesfull")

}
it('test for main func result',async ()=>{
 const result = await main.car()
 expect(result).toEqual("you can start the car") // getting result as undefined
}


Original mockedFn.key method is lost when it's reassigned, there's no way how Jest could restore it:原始mockedFn.key方法在重新分配时丢失,Jest 无法恢复它:

mockedFn.key = jest.fn()

It should be:它应该是:

jest.spyOn(mockedFn, 'key').mockImplementation(...)

If a method or property is supposed to be restored, it should never be spied/mocked by assigning jest.fn() directly.如果一个方法或属性应该被恢复,它不应该通过直接分配jest.fn()来监视/模拟它。 This especially applies to mocked globals that can cross-contaminate tests.这尤其适用于可以交叉污染测试的模拟全局变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM