嘲弄ngrx /商店 [英] Mocking ngrx/store

查看:124
本文介绍了嘲弄ngrx /商店的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于Angular 2官方发布的。我知道单元测试在beta,RC和正式版本之间发生了巨大的变化。

This is in regards to the Angular 2 official release. I know that unit testing has changed drastically between beta, RC, and the official release.

在使用单元测试时,模拟@ ngrx / store的好方法是什么?作为构造函数中的参数?它并不像模拟服务那么简单。

What's a good way to mock @ngrx/store in a unit test when it's used as a parameter in a constructor? It's not as simple as mocking a service.

例如,如果我想模拟服务,那么我可以这样做:

For example, if I wanted to mock a service, then I could do something like this:

let serviceStub = { }; // not a true mocked service, just a stub, right?

let de: DebugElement;
let el: HTMLElement;
let nativeEl: Element;
let comp: Typeahead;
let fixture: ComponentFixture<Typeahead>;

describe('Component:Typeahead', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [...],
            declarations: [Typeahead],
            providers: [
                {provide: TypeaheadService, useValue: serviceStub} // provides the service that is being "mocked"
            ]
        }).compileComponents();

        fixture = TestBed.createComponent(Typeahead);
        nativeEl = fixture.nativeElement;
        comp = fixture.componentInstance;
        de = fixture.debugElement;
    });
});

这样可行。

For ngrx / store 但是,它没有(如果你将Store替换为TypeaheadService)。我想你必须编写一个扩展Store的模拟类,然后将其提供给正在测试的组件,但我不确定为什么会这样(如果是这种情况)。

For ngrx/store, however, it does not (if you substitute Store in for TypeaheadService). I'm thinking you have to write a mock class that extends Store, and then provide that to the component that is being tested, but I'm not sure why that is the case (if that is even the case).

我很困惑如何在我的单元测试中模拟 ngrx / store 并且找不到任何他们网站或github上的文档。也许我忽略了它。

I'm just confused as how to mock ngrx/store in my unit tests and couldn't find any documentation on their site or github. Maybe I overlooked it.

推荐答案

感谢您发布问题并建议可能的解决方案!

Thank you for posting the question and suggesting a potential solution!

我嘲笑它的方法是,在每次测试之前使用实际操作来设置初始状态,即模拟状态。这是一个例子

The way I've mocked it is, to use the actual actions to set an initial state i.e. a mocked state before each test. Here's an example

beforeEach(inject([Store], (store: Store<ApplicationState>) => {
const someFakeState = {
    counter: 9,
    counterFilter: 'A_FAKE_COUNTER_FILTER'
};

store.dispatch(new myActionToSetSomeData(someFakeState));
}));

在你的 it()区块内你应该现在可以检查组件是否显示计数为9并按'A_FAKE_COUNTER_FILTER'过滤

Inside your it() block you should now be able to check that the component is displaying a count of 9 and a filtering by 'A_FAKE_COUNTER_FILTER'.

您当然可以设置it块内的状态,而不是 beforeEach ,只要它在组件实例化之前。

You can of course set the state inside your it block, rather than beforeEach, as long as its before the component is instantiated.

这篇关于嘲弄ngrx /商店的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆