Angular2 testing: change entered service value

I am testing a simple service. The service uses 2 values ​​from another service.

Basically, I would like to check these 2 values: isLogged = false and isLogged = true .

Can I just change the value of the entered service or do I need to do something else? (which I don’t know, so if you could lead me along the road, I would appreciate it).

Here is my code for testing:

EDIT I found a solution to my problem. You need to enter the provider into the paste options , and you can change its properties as you wish.

  import { TestBed, async, inject } from '@angular/core/testing';
  import { AuthGuardService } from './authguard.service';
  import { Router } from '@angular/router';

  import { AuthService } from './auth.service';

  describe('AuthguardService', () => {

    let calledUrl = '/logged/main/last';

    let authServiceStub = {
      isLogged: false,
      redirectUrl: calledUrl
    };

    class RouterStub {
      navigate(url: string) { return url; }
    };

    beforeEach(() => {
      TestBed.configureTestingModule({
        providers: [
          AuthGuardService,
          { provide: AuthService, useValue: authServiceStub },
          { provide: Router, useClass: RouterStub },
        ]
      });
    });

    it('should ...', inject([AuthGuardService, Router], (service: AuthGuardService, router: Router) => {
      let spy = spyOn(router, 'navigate');

      service.checkLoginState(calledUrl);
      expect(spy).toHaveBeenCalledWith(['/login']);
    }));
  });
+4
source share
1

- . , , , authServiceStub :

// inside tests:
authServiceStub.isLogged = false;
...
authServiceStub.isLogged = true;

^ , .

:

let isLogged: false;
let authServiceStub = {
      isLogged: isLogged,
      redirectUrl: calledUrl
    };
...
// inside tests:
isLogged = false;
...
isLogged = true;

^ , .

:

let authServiceStub = {
      isLogged: false,
      setLogged: function(logged) { this.isLogged = logged; },
      redirectUrl: calledUrl
    };
...
// inside tests:
setLogged(false);
...
setLogged(true);

^ . .

, isLogged , spyOn:

// inside tests:
spyOn(authServiceStub, "isLogged").and.returnValue(false);
...
spyOn(authServiceStub, "isLogged").and.returnValue(true);

^ /, ( - ). , . AuthService isLogged ( ).

0

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


All Articles