在angular4单元测试中处理异步调用的正确方法

时间:2017-08-28 14:38:16

标签: javascript angular unit-testing asynchronous jasmine

我一直在寻找使用Jasmine在Angular 4单元测试中测试GraphQL异步调用的正确方法。 在不使用setTimeout函数的情况下测试异步调用的正确流程是什么? 这是我当前的代码,但没有等待回复

it('shoud swap', (done) => {
const SequenceMaster = '0';
const sequenceMasterAlts = '2138';
const sKey = '[DARCARS]SS_02_VW+201701_VW';
component.swapTablesData(sKey);
  expect(component.testVariable).toBe(true);
  done();
 });

1 个答案:

答案 0 :(得分:0)

Docs解释得非常好,您可以使用fakeAsync执行此操作:

describe('test service using fakeAsync', fakeAsync(() => {
    let service: SomeService;

    beforeEach(() => {
        TestBed.configureTestingModule({ providers: [SomeService] });

        service = TestBed.get(SomeService, null);
    });

    it('should use SomeService', () => {
        let returnValue: any;
        service.doSomething().then((val: any) => returnValue = val);
        tick();
        expect(returnValue).toBe('return value using fakeAsync');
    });
});
相关问题