Mocking Service in Unit Tests

I am trying to make fun of a service for a unit test component. Here is my service:

@Injectable()
export class LoginService {

    constructor(public http: Http) { }

    getLanguages() {
        return this.http.get('the-url')
                        .map((res: Response) => res.json());
    }

...

NOTE. My component calls this method in the constructor (loads languages ​​when building comp).

Then my attempt to mock him:

class MockLoginService {
    getLanguages() {
        return Observable.of(
            [
                {
                    'name': 'English (USA)',
                    'locale': 'en-US'
                },
                {
                    'name': 'Español',
                    'locale': 'es-US'
                }
            ]
        );
    }

And my unit test component:

  it('should load languages', inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
        tcb
            .overrideProviders(LoginComponent, [ provide(LoginService, { useClass: MockLoginService })])
            .createAsync(LoginComponent).then((fixture) => {
                let element = fixture.nativeElement;
                let loginInstance = fixture.componentInstance;
                fixture.detectChanges();
                expect(loginInstance._loginService.getLanguages).toHaveBeenCalled();
                expect(element.querySelectorAll('option').length).toBe(5);
            });
    }));

Question:

I see that my mock service is being called and the received data is correct, but my 2 tests are skipped! Here is the log:

angular2 -polyfills.js: 528 Unhandled Promise rejection: 'expect' was used when there was no current specification, this may be due to the fact that the asynchronous test was disabled; Zone:; Task: Promise.then; Meaning: Error: "wait" was used when there was no current specification, this may be due to the fact that the asynchronous test was disabled (...)

, async, - . angular2 -polyfills.js: 530 : ( ): : "" , , , (...)

fakeAsync - . !

+4
1

beforeEachProviders

var service = new MockLoginService();

beforeEachProviders(() => [ provide(TestService, { useValue: service })]);

it('should load languages', inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
    tcb
        .createAsync(LoginComponent).then((fixture) => {
            let element = fixture.nativeElement;
            let loginInstance = fixture.componentInstance;
            fixture.detectChanges();

            expect(element.querySelectorAll('option').length).toBe(2);
        });
}));

. . plunkr: https://plnkr.co/edit/zTy3Ou?p=preview.

+2

All Articles