我有一个这样的函数:
class MyClass
constructor(private readonly simpleInstance: SomeOtherClass) {}
get myGetter() {
if(!simpleInstance) {
throw Error('Bad thing')
}
return simpleIntance.id
}
我想编写一个测试用例,其中simpleInstance = null
我在模拟 simpleInstance
时遇到了很多麻烦
这是我迄今为止的测试,以及我尝试过的一些选项。
Note: I am using
NestJs
so there is a dependency injection pattern within my tests which I have removed for brevity. TL;DR: an initializedSomeOtherClass
gets passed intoMyClass
during instantiation.
describe('MyClass', () => {
let myClassInstance: MyClass
let someOtherClassMock: jest.Mock<SomeOtherClass>
beforeEach(() => {
someOtherClassMock = jest.fn()
myClassInstance = new MyClass(someOtherClassMock)
})
it('should throw an error if injected simpleInstance is null', () => {
userMock = ........ // <--- Setting up the mocked value is where I have trouble
expect(() => myClassInstance.myGetter).toThrow(Error('Bad thing'))
})
})
我尝试过返回模拟值、监视 someOtherClassMock
并返回值等。
我该怎么做?
最佳答案
在这种情况下,不需要模拟。您可以简单地在 it
测试用例中使用 null
作为其 SomeOtherClass
参数显式创建实例:
it('should throw an error if injected simpleInstance is null', () => {
myClassInstance = new MyClass(null)
expect(() => myClassInstance.myGetter).toThrow(Error('Bad thing'))
})
关于javascript - Jest SpyOn 值而不是 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59940459/