如何在angular2中测试ngrx / effects类?

时间:2017-05-24 11:00:24

标签: angular testing jasmine ngrx-effects

我下面有一个ngrx /特效类。我想测试它,但是当我运行我的测试时,它不打印任何东西,但仍然通过。测试应该是当我触发一个动作TRIGGER_LOAD_NAVIGATION_ITEMS时,我应该得到模拟的结果集并返回动作类型为LOAD_NAVIGATIONS_LINKS

效果文件

view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

测试文件

import { Injectable } from '@angular/core';
import { Effect, Actions } from '@ngrx/effects';
import { NavigationActionType } from 'app/core/store/actions/navigation/navigation.action';
import { NavigationService } from 'app/core/services/navigation.service';
import 'rxjs/add/operator/switchMap';

@Injectable()
export class NavigationServiceEffect {
    @Effect()
    navigations$ = this.actions$
                        .ofType(NavigationActionType.TRIGGER_LOAD_NAVIGATION_ITEMS)
                        .switchMap( () => this.navigationService.load())
                        .map(data => ({ type: NavigationActionType.LOAD_NAVIGATIONS_LINKS, payload: data}));

    constructor(private actions$: Actions, private navigationService: NavigationService) {}
}

测试应该失败,因为预期的有效负载长度为1并且在上面的语句中等于3,因此它应该失败。但测试通过但没有记录控制台输出。我该如何测试上述文件?

1 个答案:

答案 0 :(得分:1)

您的断言是在subscribe内定义的,这使您的测试异步
事实上,你的测试可能在行动结果被解雇之前完成 要解决此问题,您需要使用async函数包装测试,如下所示:

   it('Call Load Navigation items action after Trigger Load aciton', 
      async(
        inject([
            Actions, NavigationService
        ],
            ( _actions, _navService) => {
                actions = _actions;
                navService = _navService;

                spyOn(navService, 'load')
                    .and.returnValue(Observable.of([
                        { "name": "Help", "hasChild": false, "roles": [101, 151, 201, 301, 401], "url": "help" }
                    ]));


                navEffects = new NavigationServiceEffect(actions, navService);

                navEffects.navigations$.subscribe(r => console.log(r));

                navEffects.navigations$.subscribe(result => {

                    console.log(result);
                    expect(result.type).toEqual(NavigationActionType.LOAD_NAVIGATIONS_LINKS);
                    expect(result.payload.length).toEqual(3); // This should fail

                });
            })));  

有关async here的更多信息。