我如何使用 ngRedux 测试服务 [英] How can i test service with ngRedux

查看:15
本文介绍了我如何使用 ngRedux 测试服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何模拟 ngRedux 的 getState: with karma jasmine

例如,我的服务通过 ngRedux 从商店获取价值.

this.ngRedux.getState()

解决方案

我通过监视 getState() 方法解决了这个问题:

spyOn(MockNgRedux.getInstance(), 'getState').and.returnValue({ ... });

我不知道这样做是否可行,但在我的情况下它有效.不过,我不需要模拟任何花哨的状态修改,只需一个简单的 getState().

MockNgRedux@angular-redux/store 模块的一部分.您的测试可能看起来像这样:

<预><代码>...从@angular-redux/store/lib/testing"导入 {MockNgRedux, NgReduxTestingModule};描述('MyTest',()=> {beforeEach(async(() => {TestBed.configureTestingModule({...进口:[...NgRedux 测试模块],供应商: [...MockNgRedux]}).compileComponents();}));it('做某事', () => {//设置spyOn(MockNgRedux.getInstance(), 'getState').and.returnValue({here: 'be my mock store'});spyOn(MockNgRedux.getInstance(), 'dispatch').and.stub();....期望(MockNgRedux.getInstance().dispatch).toHaveBeenCalledWith(something);});});

这是文档的链接:https://angular-redux.github.io/store/classes/mockngredux.html

How can i mock getState of ngRedux: with karma jasmine

For example my service get value from store by ngRedux.

this.ngRedux.getState()

解决方案

I solved the problem by spying on the getState() method:

spyOn(MockNgRedux.getInstance(), 'getState').and.returnValue({ ... });

I have no idea if that's the way to do it, but it worked in my case. I don't need to mock any fancy state modifications, though, just one simple getState().

MockNgRedux is part of the @angular-redux/store module. Your test could look somewhat like this:

...
import {MockNgRedux, NgReduxTestingModule} from '@angular-redux/store/lib/testing';

describe('MyTest', () => {
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            ...
            imports: [
                ...
                NgReduxTestingModule
            ],
            providers: [
                ...
                MockNgRedux
            ]
        })
        .compileComponents();
    }));

    it('does something', () => {
        // set up
        spyOn(MockNgRedux.getInstance(), 'getState').and.returnValue({here: 'be my mock store'});
        spyOn(MockNgRedux.getInstance(), 'dispatch').and.stub();
        ....
        expect(MockNgRedux.getInstance().dispatch).toHaveBeenCalledWith(something);
    });
});

Here's a link to the docs: https://angular-redux.github.io/store/classes/mockngredux.html

这篇关于我如何使用 ngRedux 测试服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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