2017-06-16 190 views
3

我想测试一个异步组件方法,我想我正确地使用了Angular 4的异步测试功能,但它不工作。我的问题是,当我运行测试时,不等待供Promise解决。看起来,函数的异步特性导致超时被触发,并且测试过早退出。无论如何,测试都会通过,因为whenStable()中的所有expect()语句都会被跳过。为什么我的异步Angular Jasmine单元测试不工作?

如果我省略了async()包装功能和开关传递一个done回调,并在whenStable()块的末尾调用它的茉莉花语法,它工作正常。谁能告诉我为什么它不适用于Angular async()包装?

我的代码如下所示:

// my.component.ts 
ngOnInit() { 
    this.getResults().then((results) => { 
    this.results = results; 
    }); 
} 

// My asynchronous function, which takes 1.5s to load results 
getResults() { 
    let promise = new Promise((resolve) => { 
    setTimeout(() => { 
     resolve('foo'); 
    }, 1500); 
    }) 
    return promise; 
} 


// my.component.spec.ts (Angular async version which doesn't work) 
it('should load results', async(() => { 
    spyOn(component, 'getResults').and.returnValue(Promise.resolve('bar')); 
    component.ngOnInit(); 

    fixture.whenStable().then(() => { 
    // Everything in here gets skipped when I run the test 
    fixture.detectChanges(); 
    // This should cause the test to fail, but it doesn't because it's not run in time 
    expect(true).toBe(false) 
    }); 
})); 

// my.component.spec.ts (Jasmine version that works) 
it('should load results', (done) => { 
    spyOn(component, 'getResults').and.returnValue(Promise.resolve('bar')); 
    component.ngOnInit(); 

    fixture.whenStable().then(() => { 
    fixture.detectChanges(); 
    // This should fail and it does because the test works using Jasmine's "done" callback 
    expect(true).toBe(false); 
    done(); 
    }); 
}); 
+0

尝试调用'夹具。 detectChanges();'而不是'component.ngOnInit();'它也会运行'ngOnInit()',因为这是你第一次调用它。 –

+0

这里有什么问题? https://plnkr.co/edit/MIDy85L9fVOtdvyXKnuS?p=preview你'getResult()'方法不会被执行,因为你嘲笑它 – yurzui

+0

@AmitChigadani谢谢,但这并不行。 '期望(true).toBe(false)'仍然通过。 – Stewart

回答

3

感谢@ yurzui的Plunker,我确定,我的问题是我在我的beforeEach()方法调用fixture.detectChanges()造成的:

beforeEach(() => { 
    TestBed.configureTestingModule({ 
     declarations: [AppComponent], 
    }); 

    fixture = TestBed.createComponent(AppComponent); 

    component = fixture.componentInstance; 

    // The following line is to blame! Removing it makes the test work correctly. 
    fixture.detectChanges(); 
}); 
+0

无论如何找出夹具的原因。 detectChanges()'不能在'BeforeEach()' –

+1

@AdamHughes这是因为在我的情况下,我需要阻止'ngOnInit()'运行。 detectChanges()会导致该方法运行。 – Stewart

相关问题