我得到一个关于我的spec文件单元测试的错误,没有成功解决,当我运行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
...但它没有解决。需要你的帮助,谢谢!
如何解决这个错误:
Cannot read properties of undefined (reading 'size')
2条答案
按热度按时间sz81bmfz1#
你需要初始化你的商店:
htrmnn0y2#
还需要初始化
provideMockStore()
中的选择器: