测试从服务返回的承诺解析



我有一个问题,测试承诺解析从函数返回的承诺。问题是。then()没有被执行。

我正在测试的组件方法:

private _openToast(): void {
this._toast
.action()
.then(
() => {
this.test();
},
() => {}
);
}

test(): void {
console.log("It's ok")
}

服务

@Injectable()
export class ToastService {
constructor(private _toast: OuterToastService) {}
action<ValueType>(context?: Partial<IToastContext>, config?: Partial<ToastConfig>): Promise<ValueType> {
return this._toast.open(); // It's material-like toast service that returns promise
}
}

和测试

describe('Component', () => {
let component: Component;
let fixture: ComponentFixture<Component>;
const MockToastService = jasmine.createSpyObj('toast', ['action']);
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [Component],
providers: [
{ provide: ToastService, useValue: MockToastService },
],
});
fixture = TestBed.createComponent(Component);
component = fixture.componentInstance;
});
})
it('should call test() if toast accepted', () => {
MockToastService.action.and.returnValue(Promise.resolve());
const spy = spyOn<any>(component, 'test');
component['_openToast']();
expect(spy).toHaveBeenCalled();
});

运行测试结果为:Expected spy test to have been called.这意味着(我相信是这样).then()不会被执行。为什么?

这意味着(我相信是这样).then()不执行。为什么?

您的测试是完全同步的,所以它没有给this.test()调用时间。MockToastService返回的promise可能处于已解决状态,但是.then回调仍然异步运行,下次微任务运行时

要解决这个问题,您需要使openToast返回一个承诺,然后让测试等待该承诺:

private _openToast(): void {
return this._toast.action().then(
() => {
this.test();
},
() => {}
);
}
it("should call test() if toast accepted", () => {
MockToastService.action.and.returnValue(Promise.resolve());
const spy = spyOn<any>(component, "test");
return component["_openToast"]().then(() => {
expect(spy).toHaveBeenCalled();
});
});

或者,您可以使用fakeAsync测试,然后强制微任务队列刷新:

import { fakeAsync, flushMicrotasks } from '@angular/core/testing';
it("should call test() if toast accepted", fakeAsync(() => {
MockToastService.action.and.returnValue(Promise.resolve());
const spy = spyOn<any>(component, "test");
component["_openToast"]();
flushMicrotasks();
expect(spy).toHaveBeenCalled();
}));

相关内容

  • 没有找到相关文章

最新更新