【问题标题】:How to verify setting a property on an interface如何验证在接口上设置属性
【发布时间】: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


【解决方案1】:

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;
}

【讨论】:

    猜你喜欢
    • 2011-07-24
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    相关资源
    最近更新 更多