我有2个服务AuthenticationStore
和NavigationStore
,它们具有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')))
);
}
}
我在做什么错了?
答案 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);
});
按上述方式修改代码后,我看到所有测试都通过了。您还可以尝试看看是否可行吗?