簡體   English   中英

在 jasmine 測試中模擬 http 服務請求 class

[英]Mock out http request of service class in a jasmine test

我的印象是,您可以使用 spyOn 方法監視 jasmine 中的服務。 然后在調用該方法后返回一個值。 但也許這想法太簡單了?

我想測試以下 nxjs 操作:

./Auth.state.ts

  // ...

  @Action(Login)
  login(ctx: StateContext<AuthStateModel>, action: Login) {
    return this.authService.login(action.payload).pipe(
      tap(({ accessToken }: { accessToken: string }) => {
        const {exp} = jwt_decode(accessToken);
        const expiresAt = dayjs().add(exp, 'second');
        ctx.patchState({
          token: accessToken,
          username: action.payload.username,
          expiresAt
        });
      })
    );
  }

該操作取決於 authService 登錄方法:

./auth.service.ts

  // ...

  login({ username, password }: User): Observable<{ accessToken?: string }> {
    return this.http
      .post(`${api.BASEURL}${api.API_LOGIN}`, { username, password });
  }

現在我的測試如下:

./Auth.state.spec.ts

describe('Auth', () => {
  let store: Store;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [NgxsModule.forRoot([AuthState]), HttpClientTestingModule],
      providers: [HttpClient, HttpHandler, AuthService]
    });

    store = TestBed.inject(Store);
  });

  function setupState(NEW_STATE = null) {
    store.reset({
      ...store.snapshot(),
      auth: NEW_STATE
    });
  }

  describe('login', () => {
    it('sets the state when login is successful', () => {
      // TS2345: Argument of type '"register"' is not assignable to parameter of type 'never'.
      spyOn(AuthService, 'login').and.returnValue(false);

      // read an workaround for it here: https://github.com/facebook/jest/issues/9675 
      // Object.defineProperty(AuthService, 'login', { get(){ return false; } });
      // but also no luck...

      const expectedState = { token: null, username: 'Some username', expiresAt: null };
      setupState();
      store.dispatch(new Login({ username: expectedState.username, password: '' }));
    
      const auth = store.selectSnapshot(state => state.auth);
      expect(auth).toEqual(expectedState);
    });
  });
  // ...

在您的Auth.state.spec.ts文件中,您應該從 angular 的TestBed獲取注入服務的實例。

describe('login', () => {
   it('sets the state when login is successful', () => {
      // Get the injected instance of AuthService
      const authService = TestBed.inject(AuthService);

      spyOn(authService, 'register').and.returnValue(of(false));

      spyOn(authService, 'login').and.returnValue(
        of({ access_token: 'scdkj2' })
      );
      // Make sure fixture.detectChanges() is not invoked before all spies are setup
      fixture.detectChanges();
      
      ....
    });
  });

暫無
暫無

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

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