问题描述
我如何模拟 ngRedux 的 getState: with karma jasmine
例如,我的服务通过 ngRedux 从商店获取价值.
this.ngRedux.getState()
我通过监视 getState() 方法解决了这个问题:
spyOn(MockNgRedux.getInstance(), 'getState').and.returnValue({ ... });
我不知道这样做是否可行,但在我的情况下它有效.不过,我不需要模拟任何花哨的状态修改,只需一个简单的 getState().
MockNgRedux
是 @angular-redux/store
模块的一部分.您的测试可能看起来像这样:
这是文档的链接: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 测试服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!