Sinon 存根函数给出错误无法读取未定义的属性

问题描述 投票:0回答:0

一个包中有一个类方法如下

async getPropertyAsync(name: string): Promise<string> {
    //do something
}

和另一个包中的另一个函数如下

function getColor(prop: string) : string {
    switch(prop.toUpperCase()) {
        //do something
        default: return 'no_color';
    }
}

在我的代码中我有

public async myFunction(): Promise<Something>{
    const colorProp = getColor(await myClass.getPropertyAsync('WHITE'));
    //do something
}

在我的测试中,我想创建

getPropertyAsync

的存根
const myClassStub = {} as MyClass;
myClassStub.myFunction = sandbox.stub().onCall(0).returns(Promise.resolve('FAKE_COLOR'));
const ret = myClassObj.myFunction();

在上面的最后一行,我在运行测试时遇到以下错误

TypeError: Cannot read properties of undefined (reading 'toUpperCase')

我认为存根没有返回对象类型为

string
,所以我尝试了以下两种方法来明确声明返回类型是一个字符串。

let myStub = sandbox.stub(someObj, 'getPropertyAsync').resolves('FAKE_COLOR' as string);

let myStub = sandbox.stub(someObj, 'getPropertyAsync').returns(Promise.resolve('FAKE_COLOR' as string));

以上均无效。他们给出了同样的错误。

typescript chai sinon stub
© www.soinside.com 2019 - 2024. All rights reserved.