簡體   English   中英

用於檢查激活路由的 Jasmine 單元測試有兩個參數和調用服務函數

[英]Jasmine Unit Test for to check activate route has two parameters and call service function

我的組件中有一個函數來獲取當前路由參數並在存在兩個參數時調用服務中的函數。

組件.ts:

listenToRouteParameters(): void {
    const state = this.route.snapshot?.queryParamMap.get('state');
    const code = this.route.snapshot?.queryParamMap.get('code');
    if (state && code) {
      const codeVerifier = this.cookieService.getCookieValue(state);
      if (codeVerifier) {
        this.cookieService.removeCookie();
        this.initiateTokenExchange(code, codeVerifier);
      } else {
        this.refreshTokens();
      }
    } else {
      this.refreshTokens();
    }

}

我為它寫了一個單元測試如下。

beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      imports: [
        FormsModule,
        ReactiveFormsModule,
        HttpClientModule,
        RouterTestingModule
      ],
      providers:[
        {
          provide: ActivatedRoute,
          useValue: {
            params: paramsSubject
          },
        },
        { provide: CookieService, useValue: cookieService}
      ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    router = TestBed.get(Router)
    route = TestBed.get(ActivatedRoute)
  });

  it('should retrieve cookie if current route has state and code params', () => {
    const activatedRoute: ActivatedRoute = fixture.debugElement.injector.get(ActivatedRoute);

    activatedRoute.queryParams = of({ state: '123' });

    fixture.detectChanges(); 
    //  tick();

    activatedRoute.queryParams.subscribe((value) => {
      expect(cookieService.getCookieValue).toHaveBeenCalled();
    })
  });

無論是否傳遞參數,此單元測試都會通過。 如果有人可以看一下並告訴我如何為該場景正確編寫單元測試,請不勝感激。

編輯:CookieService.ts

@Injectable({
  providedIn: 'root'
})
export class CookieService {

  constructor() { }

  /**
   * Set cookie
   * @param state State value
   * @param codeVerifier Code verifier value
   */
  setCookie(state: string, codeVerifier: string): void {
    document.cookie = `app.txs.${state}=${codeVerifier};secure;sameSite=strict;`;
  }

  /**
   * Get cookie value
   * @param state 
   * @returns 
   */
  getCookieValue(state: string | null): string | undefined {
    return document.cookie.split('; ').find(row => row.startsWith(`app.txs.${state}=`))?.split('=')[1];
  }

  /**
   * Remove cookie
   */
  removeCookie(): void {
    let cookies = document.cookie.split(";");
    for (let i = 0; i < cookies.length; i++){   
      let spcook =  cookies[i].split("=");
      document.cookie = spcook[0] + "=;expires=Thu, 21 Sep 1979 00:00:01 UTC;";                                
    }
  }
}

你可以做這樣的事情,跟隨評論!!:

beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      imports: [
        FormsModule,
        ReactiveFormsModule,
        HttpClientModule,
        RouterTestingModule
      ],
      providers:[
        {
          provide: ActivatedRoute,
          useValue: {
            params: paramsSubject,
            // mock snapshot as well
            snapshot: {
              queryParamMap: {
                 get: () => {}
              }
            }
          },
        },
        { provide: CookieService, useValue: cookieService}
      ]
    })
    .compileComponents();
  });

  
  it('should retrieve cookie if current route has state and code params', () => {
    // !! you don't need this line, you already have a handle on activatedRoute
    // with route = TestBed.get(ActivatedRoute)
    // const activatedRoute: ActivatedRoute = fixture.debugElement.injector.get(ActivatedRoute);

    spyOn(route.snapshot.queryParamMap, 'get').and.callFake(param => {
       // !! mock however you wish
       if (param === 'code') {
          return 1;
       } else if (param === 'state') {
          return 2;
       }
    });

    fixture.detectChanges(); 
    
    // !! if listenToRouteParameters is called in the ngOnInit
    // then you won't have to explicitly call it because the first fixture.detectChanges()
    // above calls ngOnInit
    component.listenToRouteParameters();
    
    // !! make your expectation
    expect(cookieService.getCookieValue).toHaveBeenCalled();
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM