Angular2 asynchronous testing with jasmine

I am writing an angular2 application and do not understand how to write tests for asynchronous code using jasmine. For some reason, I don't see many examples that seem terribly applicable to my situation.

I'm currently trying to test a service (not a component) that has an asynchronous dependency on another service. I am not 100% sure at what point in the test it is valid for checking the results of an asynchronous call. Can you just call expect()inside the async handler for your service?

service.foo()
    .then((data) => {
        //do I check the results in here?
        expect(data).toEqual({ a: 1, b: 2 });
        expect(mockDep.get).toHaveBeenCalled();
    });

Here is the full test.

import { TestBed, inject } from '@angular/core/testing';
import { MyService } from './my.service.ts';
import { MyDependency } from './dependency.service.ts';

class MockDependency {
    doSomething(): Promise<any> {
        throw Error('not implemented');
    };
}

describe('some tests', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                MyService,
                {
                    provide: MyDependency, useClass: MockDependency
                }
            ]
        });
    });
});

it('should do something', inject([MyService, MyDependency], (service: MyService, mockDep: MyDependency) => {
    spyOn(mockDep, 'doSomething').and.callFake(function () {
        return Promise.resolve({ a: 1, b: 2 });
    });

    service.foo()
        .then((data) => {
            //do I check the results in here?
            expect(data).toEqual({ a: 1, b: 2 });
            expect(mockDep.get).toHaveBeenCalled();
        });
}));
+4
source share
1 answer

, , , .

-, , , , , .

, , , expect then , .

, , - , ( ) . , , , , .

" ".

- . , , .

.

it('tests an async action', (done) => {
   asyncAction().then(result => {
     expect(result).toEqual(true);
     done();
   });
});

angular . , .

it('tests an async action', async(() => {
   asyncAction().then(result => {
     expect(result).toEqual(true);
   });
}));

async. - async (, promises, ..), , .

- fakeAsync, .

it('tests an async action', fakeAsync(() => {
   let myResult;
   asyncAction().then(result => {
     myResult = result;
   });

   tick();   <--- force all async actions to complete
   expect(myResult).toEqual(true);
}));

fakeAsync . tick(), " " async .
( , , ).

. angular

+14

Source: https://habr.com/ru/post/1672748/


All Articles