商店中的角度测试流

时间:2020-09-21 14:27:36

标签: angular unit-testing rxjs observable

我有2个服务AuthenticationStoreNavigationStore,它们具有user$links$流作为属性,其中links依赖于user$user$可以通过login()的{​​{1}}方法中的logout()进行调整。

服务按预期工作,我在单元测试和设置期望方面遇到问题。我的测试代码如下:

AuthenticationStore

我对`Spec ...没有期望。或第二个测试具有Admin用户的结果(例如具有上一个测试的值)。

服务代码:

NavigationStore

describe('NavigationStore', () => {
  const AuthenticationStoreService = { user$: new BehaviorSubject<User>(null) };
  let NavigationStoreService: NavigationStore;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        NavigationStore,
        {
          provide: AuthenticationStore,
          useValue: AuthenticationStoreService
        }
      ]
    })
    .compileComponents();

    NavigationStoreService = TestBed.get(NavigationStore);
  });
  it('should have Logout Admin user', async(() => {
    AuthenticationStoreService.user$.next({
      id: '',
      email: '',
      group: 'A',
    })

    NavigationStoreService.links$.subscribe(
      (links) => {
        expect(links).toEqual([
          {
            title: 'Logout',
            path: '/logout',
            acl: 'A'
          }
        ]);
      }
    );
  }));

  it('should have Login Guest user', async(() => {
    AuthenticationStoreService.user$.next({
      id: '',
      email: '',
      group: '0',
    })

    NavigationStoreService.links$.subscribe(
      (links) => {
        expect(links).toEqual([
          {
            title: 'Login',
            path: '/login',
            acl: '0'
          }
        ]);
      }
    );
  }));
});

AuthenticationStore

const links: Navigation[] = [
  { title: 'Login', path: '/login', acl: '0' },
  { title: 'Logout', path: '/logout', acl: 'A' },
];

@Injectable({
  providedIn: 'root',
})
export class NavigationStore {
  private subject = new BehaviorSubject<Navigation[]>(null);
  links$: Observable<Navigation[]> = this.subject.asObservable();

  constructor(private auth: AuthenticationStore) {
    this.links$ = this.auth.user$.pipe(
      map((user) => links.filter((link) => link.acl.includes(user ? user.group : '0')))
    );
  }
}

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

您应该尝试像这样将AuthenticationStoreService的初始化移动到第一个beforeEach中-

describe('NavigationStore', () => {
  let AuthenticationStoreService;
  let NavigationStoreService: NavigationStore;

  beforeEach(() => {
    AuthenticationStoreService = { user$: new BehaviorSubject<any>(null) };
    TestBed.configureTestingModule({
      providers: [
        NavigationStore,
        {
          provide: AuthenticationStore,
          useValue: AuthenticationStoreService
        }
      ]
    })
    .compileComponents();

    NavigationStoreService = TestBed.get(NavigationStore);
  });

按上述方式修改代码后,我看到所有测试都通过了。您还可以尝试看看是否可行吗?