繁体   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