gpt4 book ai didi

javascript - Jest SpyOn 值而不是 getter

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:24 24 4
gpt4 key购买 nike

我有一个这样的函数:

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 initialized SomeOtherClass gets passed into MyClass 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com