Angular单元测试 – 无法读取未定义的属性(读取’size’)NgRx

huangapple go评论83阅读模式
英文:

Angular Unit Testing - Cannot read properties of undefined (reading 'size') NgRx

问题

我在运行npm test时遇到了有关我的规范文件单元测试的错误,但未能成功解决。错误在karma chrome上运行时显示:

enter image description here

agent.service.spec.ts:

import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { MemoizedSelector, Store } from '@ngrx/store';
import { MockStore, provideMockStore } from '@ngrx/store/testing';
import * as fromGrid from './../grid/store/grid.reducer';

import { GridActions } from './../grid/store/grid.actions';
import { AgentService } from './agent.service';
import { GridSizeEnum } from '../models/enums/GridSize';


describe('AgentService', () => {

    let agentService: AgentService;
    let mockStore: MockStore<fromGrid.State>;
    let mockGridSizeSelector: MemoizedSelector<fromGrid.State, GridSizeEnum>;
    let size: GridSizeEnum = GridSizeEnum.GRID_1


    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule,
                RouterTestingModule
            ],
            providers: [
                AgentService,
                provideMockStore({}),

            ],
        });

        agentService = TestBed.get(AgentService);
        mockStore = TestBed.get(Store);
        mockGridSizeSelector = mockStore.overrideSelector(fromGrid.getGridSize, size);
    });

    it('should return the default state', () => {

        const action = {} as GridActions;
        const state = fromGrid.reducer(fromGrid.initialState, action);
        expect(state).toBe(fromGrid.initialState);

    });

    it('should be created', () => {

        expect(agentService).toBeTruthy();
    });

    afterEach(() => {

    })


});

agent.service.ts:

构造函数部分-

constructor(private http: HttpClient,
  private router: Router,
  private store: Store<fromRoot.State>,
  private gridStore: Store<fromGrid.State>,
  private commandWebSocket: CommandWebsocketService,
  private logService: LogService) {

  this.commandWebSocket.connect();
  this.commandWebSocket.messages$.subscribe((data) => {
    this.commandWebsocketData(data);
  });

  this.store.pipe(select(fromGrid.getGridSize), takeUntil(this.destroyed$)).subscribe((size) => {
    if (size) {
      this.gridSize = size;
    }
  });

  this.gridStore.pipe(select(fromGrid.getGridVideoStreamIDs, this.gridSize), takeUntil(this.destroyed$)).subscribe(data => {
    if (data && data.length) {
      this.gridStreamIDs = data;
      const byPassCpuIdsCopy = this.byPassCpuIds;
      this.byPassCpuIds = [];
      this.gridStreamIDs.filter((dta) => {
        this.byPassCpuIds[dta] = byPassCpuIdsCopy[dta];
      });
    }
  });
}

grid.reducer.ts:

export const getGridSize = createSelector(
  getGridFeatureState,
  state => state.size
);

这个错误在另一种情况下也经常出现,当我在constructor()ngOnInit()中订阅特定的选择器时(如果是组件单元测试的话)。

为了解决这个问题,我尝试在规范文件中初始化状态,如上面的agent.service.spec... 但没有解决。

如何解决这个错误:

无法读取未定义的属性(读取'size')?

英文:

I get an error about my spec file unit test without success to solve, the error display when I run npm test, on karma chrome:

enter image description here

agent.service.spec.ts:

import { HttpClientTestingModule } from &#39;@angular/common/http/testing&#39;;
import { TestBed } from &#39;@angular/core/testing&#39;;
import { RouterTestingModule } from &#39;@angular/router/testing&#39;;
import { MemoizedSelector, Store } from &#39;@ngrx/store&#39;;
import { MockStore, provideMockStore } from &#39;@ngrx/store/testing&#39;;
import * as fromGrid from &#39;./../grid/store/grid.reducer&#39;;
import { GridActions } from &#39;./../grid/store/grid.actions&#39;;
import { AgentService } from &#39;./agent.service&#39;;
import { GridSizeEnum } from &#39;../models/enums/GridSize&#39;;
describe(&#39;AgentService&#39;, () =&gt; {
let agentService: AgentService;
let mockStore: MockStore&lt;fromGrid.State&gt;;
let mockGridSizeSelector: MemoizedSelector&lt;fromGrid.State, GridSizeEnum&gt;;
let size: GridSizeEnum = GridSizeEnum.GRID_1
beforeEach(() =&gt; {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
RouterTestingModule
],
providers: [
AgentService,
provideMockStore({}),
],
});
agentService = TestBed.get(AgentService);
mockStore = TestBed.get(Store);
mockGridSizeSelector = mockStore.overrideSelector(fromGrid.getGridSize, size);
});
it(&#39;should return the default state&#39;, () =&gt; {
const action = {} as GridActions;
const state = fromGrid.reducer(fromGrid.initialState, action);
expect(state).toBe(fromGrid.initialState);
});
it(&#39;should be created&#39;, () =&gt; {
expect(agentService).toBeTruthy();
});
afterEach(() =&gt; {
})
});

agent.service.ts :

the constructor part-

  constructor(private http: HttpClient,
private router: Router,
private store: Store&lt;fromRoot.State&gt;,
private gridStore: Store&lt;fromGrid.State&gt;,
private commandWebSocket: CommandWebsocketService,
private logService: LogService) {
this.commandWebSocket.connect();
this.commandWebSocket.messages$.subscribe((data) =&gt; {
this.commandWebsocketData(data);
});
this.store.pipe(select(fromGrid.getGridSize), takeUntil(this.destroyed$)).subscribe((size) =&gt; {
if (size) {
this.gridSize = size;
}
});
this.gridStore.pipe(select(fromGrid.getGridVideoStreamIDs, this.gridSize), takeUntil(this.destroyed$)).subscribe(data =&gt; {
if (data &amp;&amp; data.length) {
this.gridStreamIDs = data;
const byPassCpuIdsCopy = this.byPassCpuIds;
this.byPassCpuIds = [];
this.gridStreamIDs.filter((dta) =&gt; {
this.byPassCpuIds[dta] = byPassCpuIdsCopy[dta];
});
}
});
}

grid.reducer.ts :

export const getGridSize = createSelector(
getGridFeatureState,
state =&gt; state.size
);

This error appears a lot in another case, when I have subscribe to specific selector at constructor() or at ngOnInit() (if it component unit test ).

For solution i tried to initial the state in spec file, see above in agent.service.spec... but it isn't solved.
Need your help, thanks!

How can i solve this error:

Cannot read properties of undefined (reading &#39;size&#39;)

答案1

得分: 0

你需要初始化你的存储:

provideMockStore({
grid: {     // 假设 'grid' 是你的功能键
size: 5
}
})
英文:

You need to initialize your store:

provideMockStore({
grid: {     // assuming &#39;grid&#39; is your feature key
size: 5
}
})

答案2

得分: 0

也需要在provideMockStore()函数中初始化选择器:

    provideMockStore({
         initialState: fromGrid.initialState,
         selectors: [
             {
                selector: fromGrid.getGridSize,
                value: GridSizeEnum.GRID_1
             }
         ]
     }),
英文:

also need to initialize the selectors in provideMockStore():

provideMockStore({
initialState: fromGrid.initialState,
selectors: [
{
selector: fromGrid.getGridSize,
value: GridSizeEnum.GRID_1
}
]
}),

huangapple
  • 本文由 发表于 2023年4月13日 17:50:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76004038.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定