我有这样的功能:
class MyClass
constructor(private readonly simpleInstance: SomeOtherClass) {}
get myGetter() {
if(!simpleInstance) {
throw Error('Bad thing')
}
return simpleIntance.id
}
我想写一个测试用例,其中simpleInstance = null
我在嘲笑simpleInstance
到目前为止,这是我的测试,还有我尝试过的一些选项。
注意:我使用的是
NestJs
,所以为了简洁起见,在我的测试中有一个依赖项注入模式。 TL; DR :初始化的SomeOtherClass
在实例化过程中传递到MyClass
中。
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
并返回值,等等。
我该怎么做?
答案 0 :(得分:1)
在这种情况下,不需要模拟。您可以在null
测试用例中,使用SomeOtherClass
为其参数it
显式创建实例:
it('should throw an error if injected simpleInstance is null', () => {
myClassInstance = new MyClass(null)
expect(() => myClassInstance.myGetter).toThrow(Error('Bad thing'))
})