【问题标题】:Angular 4 Output test not giving expected resultAngular 4 输出测试未给出预期结果
【发布时间】:2018-08-29 18:36:35
【问题描述】:

我有一个组件。它将一个值作为其@Input。如果调用了 onDelete() 方法,则有一个 EventEmitter 将发出放入的值。我正在尝试为这个组件编写一个测试,我从发射器获得的值是未定义的,而不是我传递的值.

这里是测试:

import { CheckedComponent } from '../checked/checked.component'; 

describe('CheckedComponent', () => {
    it('emits the input value on delte', () => {
        let total = null; 
        const component = new CheckedComponent(); 
        component.item = 'example'; 
        component.delete.subscribe(item => {
            total = item; 
        });
        component.onDelete()
        console.log("HERE", total)
        expect(total).not.toBeNull();
        // expect(total).toEqual('example'); 
    }); 
});  

注释行不起作用。总计等于“未定义”,而不是“示例”。有趣的是,如果我使用 console.log(component.item),我仍然会得到“示例”数据。

这是实际的组件:

import { Component, Input, Output, EventEmitter } from '@angular/core'; 

@Component({
    templateUrl: './checked.component.html', 
    selector: 'checked', 
    styleUrls: ['./checked.component.css']
})

export class CheckedComponent {
    @Input('item') item; 
    @Output() delete = new EventEmitter()

    onDelete() {
        this.delete.emit(this.item.value)
    }
}

不确定我在这里做错了什么。在 Angular 4 中进行测试的半新手。任何指导将不胜感激。谢谢!

【问题讨论】:

  • 我喜欢那些出于完全任意的原因而对问题投反对票的人。它使 stackoverflow 成为一个非常愉快的寻求帮助的地方。我的问题不合理吗?不,不是。
  • 我刚刚投了赞成票。我不明白为什么这不是一个好问题。

标签: angular karma-jasmine


【解决方案1】:

当您发出this.delete.emit(this.item.value) 时,您需要在单元测试中为item 分配适当的值。如下更新您的单元测试代码。

const component = new CheckedComponent(); 
component.item =  { value : 'example'}; 

您应该期望 subscribe 方法中的值。因为“total”的值以后可能会被赋予“item”的值。

import { CheckedComponent } from '../checked/checked.component'; 
describe('CheckedComponent', () => {
  it('emits the input value on delte', () => {
    let value = null; 
    const component = new CheckedComponent(); 
    component.item =  { value : 'example'}; 
    component.delete.subscribe(item => {
        value= item; 
        console.log("HERE", total)
        expect(value).not.toBeNull();
        expect(value).toEqual('example');
    });
    component.onDelete()
  }); 
});

【讨论】:

  • 当您发出 this.delete.emit(this.item.value) 时,您需要在单元测试中为项目分配适当的值。
【解决方案2】:

问题在于组件需要一个具有 VALUE 的对象,而不是纯值。这修复了它:

component.item = {value: 'example'};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 2016-01-30
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多