ngrx测试方法触发操作。

6

我有一个服务,其中包含一个方法,当调用该方法时,将分派一个操作

export default class AuthService {
  constructor(private store: Store<IAppState>, private jwtService: JWTService) {}

  public isSessionValid = (id_token?: string, access_token?: string): Observable<boolean> => {
    const hasValidSession: boolean = this.jwtService.isTokenValid(id_token);

    if (!hasValidSession) {
      this.invalidateSession();
      return of(false);
    }

    this.setupValidSession(id_token, access_token);
    return of(true);
  }

  public invalidateSession = (): void => {
    this.store.dispatch(new InvalidSession());
  }

  public setupValidSession = (id_token?: string, access_token?: string): void => {
    this.store.dispatch(new ValidSession());

    if (id_token && access_token) {
      this.store.dispatch(
        new PersistSessionTokens({
          [ID_TOKEN_STORAGE_KEY]: id_token,
          [ACCESS_TOKEN_STORAGE_KEY]: access_token,
        })
      );
    }
  }
}

我想在我的测试中断言,如果调用了invalidateSession,则会触发一个动作。

然而,我的尝试编写测试却返回预期的间谍分派已被调用

我的规范文件如下:

import { TestBed } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

import AuthService from './auth.service';
import JWTService from '../jwt/jwt.service';
import { Store } from '@ngrx/store';

describe('AuthService', () => {
  describe('isSessionValid', () => {
    it('should call isTokenValid on the jwtService with an id_token', () => {
      const { authService, jwtService, props } = setup({ id_token: '123' });
      const jwtServiceSpy = spyOn(jwtService, 'isTokenValid');
      authService.isSessionValid(props);

      expect(jwtServiceSpy).toHaveBeenCalledWith({ id_token: '123' });
    });

    it('should call invalidateSession if hasValidSession is false', () => {
      const { authService, jwtService, props } = setup({});
      spyOn(jwtService, 'isTokenValid').and.returnValue(false);
      const authServiceInvalidSessionSpy = spyOn(authService, 'invalidateSession');
      authService.isSessionValid(props);

      expect(authServiceInvalidSessionSpy).toHaveBeenCalled();
    });

    it('should call setupValidSession if hasValidSession is true', () => {
      const { authService, jwtService, props } = setup({});
      spyOn(jwtService, 'isTokenValid').and.returnValue(true);
      const authServicehasValidSessionSpy = spyOn(authService, 'setupValidSession');
      authService.isSessionValid(props);

      expect(authServicehasValidSessionSpy).toHaveBeenCalled();
    });
  });

  describe('invalidateSession', () => {
    it('should dispatch the InvalidSession action', () => {
      const { authService, jwtService, props, store } = setup({});

      spyOn(jwtService, 'isTokenValid').and.returnValue(false);
      const authServiceInvalidSessionSpy = spyOn(authService, 'invalidateSession');
      const storeSpy = spyOn(store, 'dispatch');
      authService.invalidateSession();

      expect(storeSpy).toHaveBeenCalled();
    });
  });

  const setup = propOverrides => {
    TestBed.configureTestingModule({
      providers: [
        AuthService,
        {
          provide: JWTService,
          useClass: MockJWTService,
        },
        { provide: Store, useClass: MockStore },
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    }).compileComponents();

    const props = Object.assign({}, { ...propOverrides });

    const authService = TestBed.get(AuthService);
    const jwtService = TestBed.get(JWTService);
    const store = TestBed.get(Store);

    return { authService, jwtService, props, store };
  };
});

export class MockJWTService {
  isTokenValid(id_token?: string) {}
}

export class MockStore {
  select() {}
  dispatch() {}
}

我正在试图在invalidateSession描述块内进行测试

1个回答

0
在你的例子中,问题是你模拟了spyOn(authService, 'invalidateSession');,因此它的原始逻辑没有被调用,所以没有任何分发。

对于这样的测试,我通常使用ng-mocks

它可以通过几个调用来设置模拟环境。

beforeAll(() => MockBuilder(
  AuthService,
  [AuthServiceModule, StoreModule.forRoot({})],
));

it('dispatches an action', () => {
  const dispatchSpy = MockInstance(
    Store,
    'dispatch',
    jasmine.createSpy(),
  );

  const service = TestBed.inject(AuthService);
  const store = TestBed.inject(Store);

  service.invalidateSession();
  expect(dispatchSpy).toHaveBeenCalledWith(
    new InvalidSession(),
  );
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接