【问题标题】:Not able to change a component's property from unit test无法从单元测试中更改组件的属性
【发布时间】:2018-02-15 12:19:44
【问题描述】:

我正在尝试编写一个测试,以确保我的方法根据组件的属性之一返回正确的值。 所以在我的单元测试中,我想设置组件属性的值,然后调用组件的方法,该方法应该基于该值返回一个布尔值,但是它没有按预期工作。

组件的方法很简单:

isLoading(): boolean {
    return this.matches === [];
}

这是我当前的单元测试:

it('should have isLoading reflect whether there are matches', () => {
    expect(component.matches).toBeDefined();

    component.matches = [];
    console.log(component.isLoading());
    expect(component.isLoading()).toEqual(true);

    component.matches = [{name: 'object'}];
    console.log(component.isLoading());
    expect(component.isLoading()).toEqual(false);
});

console.logs 都输出 false,我不知道为什么。

【问题讨论】:

  • Plunkr 总是有帮助 :)
  • 请考虑为后代重新表述这个问题。这些不是属性,它们是属性。好吧,这听起来可能很迂腐,但在实践中,这种区别在 Angular 模板语言的上下文中非常重要。

标签: angular jasmine karma-runner karma-jasmine angular2-testing


【解决方案1】:

我错误地假设 [] == []

在 javascript 中,将对象(包括数组)与 == 或 === 进行比较会检查它们是否是同一个对象,在这种情况下它们不是。

Why isn't [1,2,3] equal to itself in Javascript?

【讨论】:

    【解决方案2】:

    如果matches 未定义或为空,则它不是数组类型。 所以你可能会比较:

    if (this.matches is an array and empty)...
    // but if it is not initialized (undefined) or initialized as null...
    

    试试:

    isLoading(): boolean {
        return !this.matches || (this.matches && this.matches === []);
        // i would leave the () brackets to make it easier to read
    }
    

    或例如:

    isLoading(): boolean {
        return !this.matches || !this.matches.length;
    }
    

    查看你声明this.matches的位置。 例如。在构造函数中:

    constructor(
        public matches: any[] = null
    ) {}
    

    或:

    export class MyComponent {
        public matches: any[] // <- undefined, not initialized
    

    【讨论】:

    • 我很生气并假设 [] == [] 它没有
    猜你喜欢
    • 2022-01-09
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    • 2017-10-29
    • 1970-01-01
    相关资源
    最近更新 更多