简体   繁体   中英

How to mock a variable using jasmine spy?

I am trying to test a login component. I can mock everything except string variables. How to do this?

@Component({
   selector: 'app-login',
   templateUrl: './login.component.html',
   styleUrls: ['./login.component.scss'])

   export class LoginComponent {
   username: string;
   password: string;
   loginSpinner: boolean;

   constructor(public authService: AuthService, public router: Router) {
   }

   login() {
     this.loginSpinner = true;
     this.authService.login(this.username, this.password).subscribe(() => {
     this.loginSpinner = false;
     if (this.authService.isLoggedIn) {
     // Get the redirect URL from our auth service
     // If no redirect has been set, use the default
     const redirect = this.authService.redirectUrl ? this.authService.redirectUrl : '/';

     // Redirect the user
     this.router.navigate([redirect]);
    }
  }, () => {
  // also want to hide the spinner on an error response from server when attempting login
     this.loginSpinner = false;
  });
 }

   logout() {
     this.authService.logout();
    }
}

The login component has a service called authService. I am able to mock everything except the string within authService called redirect URL. How to do this?

import {LoginComponent} from './login.component';
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA} from '@angular/core';
import {AuthService} from './auth.service';
import {HttpClient, HttpHandler} from '@angular/common/http';
import {JwtHelperService, JwtModule, JwtModuleOptions} from '@auth0/angular-jwt';
import {TokenService} from './token.service';
import {Router} from '@angular/router';
import {Observable, of} from 'rxjs';


describe('LoginComponent', () => {
    let component: LoginComponent;
    let fixture: ComponentFixture<LoginComponent>;

    const JWT_Module_Options: JwtModuleOptions = {
        config: {
            tokenGetter: function () {
                return '';
            },
            whitelistedDomains: []
        }
    };

    const authServiceSpy = jasmine.createSpyObj('AuthService', ['login', 'isLoggedIn']);

    authServiceSpy.login.and.callFake(function () {
        return of({});
    });

    beforeEach(async(() => {

        TestBed.configureTestingModule({
            imports: [
                JwtModule.forRoot(JWT_Module_Options)
            ],
            declarations: [LoginComponent],
            providers: [HttpClient, HttpHandler, JwtHelperService, TokenService,
                [
                    {
                        provide: AuthService,
                        useValue: authServiceSpy
                    },

                    {
                        provide: Router,
                        useClass: class {
                            navigate = jasmine.createSpy('navigate');
                        }
                    }]],
            schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
        }).compileComponents();
    }));

    beforeEach(() => {


        fixture = TestBed.createComponent(LoginComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });

    it('should log in properly without redirect URL', () => {


        authServiceSpy.isLoggedIn.and.callFake(function () {
            return true;
        });
        component.login();

        expect(component.router.navigate).toHaveBeenCalledWith(['/']);
        expect(component.loginSpinner).toEqual(false);

    });

    it('should log in properly with redirect URL', () => {


        authServiceSpy.isLoggedIn.and.callFake(function () {
            return true;
        });


        // this doesn't work
        authServiceSpy.redirectUrl = '/foo';

        component.login();


        expect(component.router.navigate).toHaveBeenCalledWith(['/foo']);
        expect(component.loginSpinner).toEqual(false);

    });

   }
);

Can you try this?

Create a mock class:

class MockAuthService{
     public redirectUrl = "/foo";

     isLoggedIn(){
         /*This can also be defined only for spies*/
         return true;
     }
}

In your test:

describe('LoginComponent', () => {
    ...
    let mockAuthService = new MockAuthService();
    ...

    beforeEach(async(() => {
       TestBed.configureTestingModule({
          imports: [...],
          declarations: [...],
          providers: [...,
            [
              {
                   provide: AuthService,
                   useValue: mockAuthService
              },
            ]],
        schemas: [...]
    }).compileComponents();
    ....
    it('should log in properly with redirect URL', () => {
        mockAuthService.redirectUrl = '/foo';
        component.login();
        expect(component.router.navigate).toHaveBeenCalledWith(['/foo']);
        expect(component.loginSpinner).toEqual(false);
    });
    ...

Try this:

const spy = spyOnProperty(authServiceSpy, 'redirectUrl').and.returnValue(
  '/foo'
);
expect(authServiceSpy.redirectUrl).toBe('/foo');
expect(spy).toHaveBeenCalled();

I'm a tad late to the party, but there is a much simpler way to do this with what you already have. No need to set up another class. First define a variable like this:

let authService: AuthService;

Then once the testbed has been set up, set this to the actual service being used by the TestBed inside the last beforeEach() :

authService = TestBed.get(AuthService);

and finally use it in your test to set whatever you want on .redirectUrl :

// this doesn't work
authServiceSpy.redirectUrl = '/foo';
// this DOES work
authService.redirectUrl = '/foo';

Working StackBlitz .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM