我收到一个关于我的规范文件单元测试的错误,但没有成功解决,当我运行
npm test
时显示错误,在 karma chrome
:
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()
订阅特定的选择器(如果它是组件单元测试)。
对于解决方案,我尝试在 spec 文件中初始化状态,请参阅上面的
agent.service.spec
......但它没有解决。
需要你的帮助,谢谢!
我该如何解决这个错误:
Cannot read properties of undefined (reading 'size')
您需要初始化您的商店:
provideMockStore({
grid: { // assuming 'grid' is your feature key
size: 5
}
})
还需要初始化
provideMockStore()
中的选择器:
provideMockStore({
initialState: fromGrid.initialState,
selectors: [
{
selector: fromGrid.getGridSize,
value: GridSizeEnum.GRID_1
}
]
}),