gpt4 book ai didi

angular - 为什么我的异步 Angular Jasmine 单元测试不工作?

转载 作者:太空狗 更新时间:2023-10-29 18:20:10 26 4
gpt4 key购买 nike

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

如果我省略 async() 包装函数并切换到传入 done 回调的 Jasmine 语法,并在 whenStable 结束时调用它() block ,它工作正常。谁能告诉我为什么它不适用于 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();
});
});

最佳答案

感谢@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();
});

关于angular - 为什么我的异步 Angular Jasmine 单元测试不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44588765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com