【发布时间】:2020-05-26 19:47:48
【问题描述】:
我有如下界面
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 和打字稿的新手)
整个测试方法:
// 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();
【问题讨论】:
-
你能展示你的整个测试文件吗?
-
@PaulPicard 更新
-
@IgorMeszaros 您的问题有几个问题。不清楚你到底在问什么,首先你展示一段代码,然后是完全不同的一段,哪一个不起作用,究竟是什么?此外,
expect(command1).toHaveBeenCalled();没有意义,因为您希望调用对象?可以调用函数,但不能调用对象。 -
@YuriyKravets 我想知道如何验证 disabled 属性是否已在测试中被修改。我尝试的 3 种方法都没有奏效,最后一点代码是我使用 spyOnProperty 进行的整个测试,正如我在第三个示例中所说的那样。
expect(command1).toHaveBeenCalled();是我的错误,我会纠正它 -
@IgorMeszaros
toHaveBeenCalled()需要一个函数,而不是对象或对象的属性。toHaveBeenCalled()的示例用法是component.updateEnabledState。完整示例:expect(component.updateEnabledState).toHaveBeenCalled();。如果要检查属性command1.disabled是否已更改,则应调用更改它的函数(我怀疑这是updateEnabledState所做的),然后是expect(command1.disabled).toBeFalse();。
标签: angular typescript jasmine