Angular 2 - 测试子组件中事件的回调

时间:2016-12-29 10:39:06

标签: unit-testing angular jasmine

我有一个包含1个子组件的组件。像这样的东西:

<custom-component (customEvent)="foo()"></custom-component>

foo 是一个做东西的函数,假设是一个简单的增量。

我想编写一个单元测试,确保在发出自定义事件后,实际发生了增量。

我目前在测试中尝试做的事情是这样的:

let oldValue = component.variableThatShouldBeIncremented;
childComponent.onCustomEvent.emit();
expect(component.variableThatShouldBeIncremented).toBeGreaterThan(oldValue);

这目前无效。但是,如果我在一个setTimeout中包含expect,它会。这是有道理的,因为事件是异步的。

我想摆脱setTimeout。有没有办法告诉&#34;等到事件回调已经完成&#34;?

我试图寻找示例,但我只发现了检查已发出特定事件的测试,而不是检查发出特定事件的后果。

修改

我认为yurzui的回答是正确的。代码应该工作。我通过简化Q的代码而忽略了实际导致问题的代码:foo函数。

该函数正在从服务调用函数,并且它不是一个简单的增量。

出于参考目的,我的实际问题是为服务的模拟版本创建的间谍没有在事件处理程序中注册对函数的调用。问题现在解决了

2 个答案:

答案 0 :(得分:1)

您需要使用异步并使用tick:

在你的测试中:

    it( 'should work', fakeAsync( () => {

        let oldValue = component.variableThatShouldBeIncremented;
        childComponent.onCustomEvent.emit();
        tick(10); // fast forward 10 milliseconds considering that emit would take 10 milliseconds 

          expect(component.variableThatShouldBeIncremented).toBeGreaterThan(oldValue);
    } ) );

顺便说一下,我假设你正在做这个增量而只是为了看看你的订阅是否有效,在这种情况下,一个更好的办法是:

 it( 'should work', fakeAsync( () => {

    childComponent.customEvent.subscribe((data)=>{
       expect(data).toBe('what ever you expect to be emitted');
    });
    childComponent.onCustomEvent.emit();

 } ) );

如果没有,请忽略这一点。

答案 1 :(得分:1)

它应该工作。您确定使用变量的正确名称吗?例如,如果您有以下模板

<custom-component (customEvent)="foo()"></custom-component>

然后您的输出事件应如下所示:

@Output('customEvent') onCustomEvent = new EventEmitter();

最后,您的测试将通过 James Fish

it('should work', () => {
  let oldValue = component.variableThatShouldBeIncremented;
  childComponent.onCustomEvent.emit();
  expect(component.variableThatShouldBeIncremented).toBeGreaterThan(oldValue);
});