【问题标题】:ngrx/store - testing, throw TypeError: Cannot read property 'pipe' of undefinedngrx/store - 测试,抛出 TypeError:无法读取未定义的属性“管道”
【发布时间】:2020-01-29 10:40:53
【问题描述】:

这是我的 ts 文件:

this.store.pipe(select(subscribe.getRegCategories)).pipe(takeUntil(this.ngUnsubscribe)).subscribe(data => {
            if (data && data.length) {
                this.allRegCategories = data;
            }
        });

当我去测试得到错误为:

this.store.pipe(select(subscribe.getRegCategories)).pipe(takeUntil(this.ngUnsubscribe)).subscribe(data => {

TypeError: Cannot read property 'pipe' of undefined

这里如何提供管道?解决这个问题的正确方法是什么?

这是我的测试规范文件:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Store, select } from '@ngrx/store';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientModule } from '@angular/common/http';
import { ShellViewProgMgmtComponent } from './shell-view-prog-mgmt.component';
import { ViewProgMgmtComponent } from './../../components/view-prog-mgmt/view-prog-mgmt.component';
import * as actions from './../../state/actions/setup-config.actions';

describe('ShellViewProgMgmtComponent', () => {
    let component: ShellViewProgMgmtComponent;
    let fixture: ComponentFixture<ShellViewProgMgmtComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [ShellViewProgMgmtComponent, ViewProgMgmtComponent],
            imports: [HttpClientModule, RouterTestingModule],
            providers: [
            {
                provide: Store,
                useValue: {
                    dispatch: jest.fn(),
                    pipe: jest.fn()
                }
            }
            ]
        })
        .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(ShellViewProgMgmtComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });

    describe('ngOnInit()', () => {

        it('should dispatch an event resetEditPage action in ngOnit lifecycle', () => {

            const store = TestBed.get(Store);
            const action = actions.resetEditPage();
            const spy = jest.spyOn(store, 'dispatch');

            fixture.detectChanges();
            expect(spy).toHaveBeenCalledWith(action);

        });

    });
});

【问题讨论】:

  • 您是否创建了 Store 类型的实例?就像我们在 Angular 构造函数中所做的一样!

标签: angular typescript ngrx angular8 angular-unit-test


【解决方案1】:

请不要模拟您自己的商店。

改为使用MockStore 和/或模拟选择器,因为它会让您的生活更轻松。 如果这是您想要的,您可以查看实现以了解如何创建模拟商店。

https://ngrx.io/guide/store/testing

【讨论】:

  • @timdeschryer,谢谢你的建议!!是的,我实现了文档。但是当这个用户得到一个问题:https://stackoverflow.com/questions/58172016/typeerror-actual-subscribe-is-not-a-function - 你能帮我解决这个问题吗?我不想像我一样创建与问题匹配的新问题
猜你喜欢
  • 2020-01-17
  • 2021-01-22
  • 1970-01-01
  • 1970-01-01
  • 2018-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多