如何验证在接口上设置 属性

How to verify setting a property on an interface

我有如下界面

   export interface Command {
   id: CommandId;
   disabled: boolean;
}

我想测试一下禁用已经called/changed了。我尝试了以下方法:

1) 创建一个对象并检查属性是否已经改变:

const command1: Command = {id: CommandId.Print, disabled: false};
// some stuff inbetween (see below)
expect(command1.disabled).toBe(true);

结果:

TypeError: Cannot set property 'disabled' of undefined

2) 使用 typemock 创建 Mock:

const command1 = Mock.ofType<Command>();
command1.setup(x => x.id).returns(() => CommandId.Print);
// some stuff inbetween (see below)
command1.verify(x => x.disabled, Times.once());

结果:

TypeError: 'set' on proxy: trap returned falsish for property 'disabled'

3) 使用 spyOn属性:

const command1 = {id: CommandId.Print, disabled: false} as Command;
spyOnProperty(command1, 'disabled');
// some stuff following (see below)

结果:

错误:属性 disabled 没有访问类型 get

我没主意了,如何验证这样的东西? (我是 Angular 和打字稿的新手)

整个测试方法:

// arrange
const command1 = {id: TaskCommandId.Print, disabled: false} as Command;
spyOnProperty(command1, 'disabled');
const command2 = {id: CommandId.SaveTemplate, disabled: false } as Command;
spyOnProperty(command2, 'disabled');

const commands = [command1, command2];
mockService.setup(x => x.getCommands()).returns(() => commands);
const command1Update = {id: CommandId.Print, disabled: true } as CommandState;
component.ngOnInit();

// act
component.updateEnabledState(command1Update);

// assert
expect(command1.disabled).toHaveBeenCalled();
expect(command2.disabled).not.toHaveBeenCalled();

toHaveBeenCalled()是检查函数是否被调用,例如:

spyOn(component, 'someFn').and.callThrough();
component.ngOnInit();
expect(component.someFn).toHaveBeenCalled();

上面的代码应该可以在组件的 ngOnInit 中调用 someFn,例如:

ngOnInit() {
    someFn();
}
someFn() {
    console.log('1');
}

要检查某个对象的某些 property 是否已更改,您必须检查确切的 属性,例如:

component.obj = {disabled: false};
component.ngOnInit();
expect(component.obj.disabled).toBeTrue();

上面的代码应该可以在您的组件中使用以下代码:

obj: any;
ngOnInit() {
    this.obj.disabled = true;
}