我有以下界面
export interface Command {
id: CommandId;
disabled: boolean;
}
我想测试是否已在其上调用/更改了残疾人。我尝试了以下方法:
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)使用spyOnProperty:
const command1 = {id: CommandId.Print, disabled: false} as Command;
spyOnProperty(command1, 'disabled');
// some stuff following (see below)
结果:
错误:禁用的属性没有访问类型获取
我没主意,如何验证这样的东西?(我是Angular和Typescript的新手)
整个测试方法:
// 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();
上面的代码可以在您组件的someFn
内部调用ngOnInit
,但是:
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;
}