我正在使用Angular 4和NgRx 4创建一个Web应用程序,我在单元测试方面遇到了一些问题。
我在下面创建了测试,看看是否可以获得效果的返回值:
it('should load orders and call load orders complete action', fakeAsync(() => {
let responsePayload;
const mockData = [{ id: 1 }, { id: 2 }, { id: 3 }];
const orderService = TestBed.get(OrderService);
const testScheduler = new TestScheduler(null);
orderService.getAllOrders.and.returnValue(hot('a|', { a: mockData }));
actions = Observable.of(new orderActions.LoadAllOrdersAction(new Date()));
const subscription = effects.loadAllOrders$.subscribe((result: orderActions.LoadAllOrdersCompleteAction) => {
responsePayload = result.payload;
});
getTestScheduler().flush();
tick();
expect(responsePayload).toEqual(mockData);
subscription.unsubscribe();
}));
这就是我正在测试的效果:
@Injectable()
export class OrderEffect {
@Effect()
loadAllOrders$: Observable<Action> = this.actions.ofType(orderActions.LOAD_ALL_ORDERS)
.withLatestFrom(this.store$) // Get the latest state from the store and add as the second value of the array below
.switchMap((input: any[]) => {
const action: orderActions.LoadAllOrdersAction = input[0];
const store: AppState = input[1];
return Observable.timer(0, store.orders.pollingInterval) // Timer to create the polling effect.
.switchMap(() => this.orderService.getAllOrders(action.payload)
.map((orders: Array<any>) => new orderActions.LoadAllOrdersCompleteAction(orders))
.catch(error => Observable.throw(new orderActions.LoadAllOrdersFailAction(error)))
);
});
constructor(private actions: Actions, private orderService: OrderService, private store$: Store<AppState>) { }
}
但是,当我运行此测试时,我收到以下错误:Expected undefined to equal [ Object({ id: 1 }), Object({ id: 2 }), Object({ id: 3 }) ].
如果我将测试的这一行改为:orderService.getAllOrders.and.returnValue(hot('a|', { a: mockData }));
:orderService.getAllOrders.and.returnValue(Observable.of(mockData));
那么一切正常,所以我认为我在做大理石测试时出错了。
请注意,我使用jasmine-marbles
导入hot
和cold
个功能。
以下是正在运行的测试的完整代码。
it('should load orders and call load orders complete action', fakeAsync(() => {
let responsePayload;
const mockData = [{ id: 1 }, { id: 2 }, { id: 3 }];
const orderService = TestBed.get(OrderService);
const testScheduler = new TestScheduler(null);
orderService.getAllOrders.and.returnValue(Observable.of(mockData));
actions = Observable.of(new orderActions.LoadAllOrdersAction(new Date()));
const subscription = effects.loadAllOrders$.subscribe((result: orderActions.LoadAllOrdersCompleteAction) => {
responsePayload = result.payload;
});
tick();
expect(responsePayload).toEqual(mockData);
subscription.unsubscribe();
}));