gpt4 book ai didi

typescript - 在 Typescript 中使用 SinonJS 时,私有(private)属性被报告为缺失

转载 作者:行者123 更新时间:2023-12-03 17:28:42 27 4
gpt4 key购买 nike

我正在尝试使用 sinon.createStubInstance stub 类实例但我收到一条错误消息,指出缺少私有(private)成员变量。当然,我也不能明确设置它,因为它是私有(private)成员。

示例类:

class Foo {
private readonly bar: string;

constructor(bar: string) {
this.bar = bar;
}
}

class Parent {
foos: Foo[];

constructor(foos: Foo[]) {
this.foos = foos;
}
}

在测试中,我正在写 beforeEach堵塞:
beforeEach(function () {
const stubFoo = sinon.createStubInstance(Foo);

const stubParent = sinon.createStubInstance(Parent);
stubParent.foos = [stubFoo]; // Tslint error here
});

Tslint 错误是:

Property 'bar' is missing in type 'SinonStubbedInstance' but required in type 'Foo'



作为记录,我使用的是 Typescript v3.0.3 和 Sinon v7.4.1。

最佳答案

我个人喜欢this solution由 Github 用户 (paulius-valiunas) 发现:

if you just want to use this in a couple places, a simpler and more readable solution would be to use the type alias StubbedClass<T> = SinonStubbedInstance<T> & T directly. For example:

export type StubbedClass<T> = SinonStubbedInstance<T> & T;
const myStub = sinon.createStubInstance(MyClass) as StubbedClass<MyClass>;

or just:

const myStub = sinon.createStubInstance(MyClass) as SinonStubbedInstance<MyClass> & MyClass;

比其他建议更清洁、更简单!

关于typescript - 在 Typescript 中使用 SinonJS 时,私有(private)属性被报告为缺失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58100616/

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