我正在嘗試更新專案,我撰寫了一個函式,該函式從商店獲取專案并根據用戶使用this.name和this.price的選擇更新新專案,但用于更新的 item.id 相同。
public updateItemData(){
return this.store.select(itemSelector).subscribe(item => {
this.updatedItem = {
id: item.id,
name: this.name,
price: this.price
}
})
}
這可以完美地作業,沒有任何問題,但在單元測驗中。
it('should create', () => {
expect(component).toBeTruthy();
});
它標記為綠色,但顯示錯誤。
TypeError: Cannot read properties of undefined (reading 'id')
當我運行該專案時,我沒有收到有關“未定義屬性”或其他任何錯誤的任何錯誤。我開始寫測驗
請幫助解決這個問題。我會感激的。
uj5u.com熱心網友回復:
為商店服務選擇添加一個 spyOn。內部測驗或 beforeEach
spyOn(store, 'select').and.returnValue(YOUR_VALUE);
確保在里面宣告存盤和分配值beforeEach
let store: Store;
store = TestBed.inject(Store); // inside beforeEach
uj5u.com熱心網友回復:
您可以像這樣使用provideMockStore提供的ngrx:
yourcomponent.component.spec.ts
import { provideMockStore } from '@ngrx/store/testing';
describe('...', () => {
...
...
const myMockItemSelectorValue = {...};
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [...],
imports: [...],
providers: [
{
initialState: { items: {...}, users: {...} }, // an initial mock Store
selectors: [{ selector: itemSelector, value: myMockItemSelectorValue }]
}
]
})
})
});
jasmine或者使用如下方式創建商店的模擬:
const mockStore = jasmine.createSpyObj<Store>('Store', ['select']);
beforeEach(() => mockStore.select.and.retunValue(of(TheDesiredMockValue))
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{ provide: Store, useValue: mockStore }]
})
})
就個人而言,我更喜歡第一個選項,因為我可以使用selectors具有初始模擬狀態的相應模擬值指定多個。
uj5u.com熱心網友回復:
我所要做的就是
if(this.item === undefined)
{
return
}
所以在我的 component.ts
public updateItemData(){
return this.store.select(itemSelector).subscribe(item => {
if(this.item === undefined)
{
return
}
this.updatedItem = {
id: item.id,
name: this.name,
price: this.price
}
})
}
所有錯誤都消失了,使用overrideSelector模擬成功。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/522013.html
標籤:有角度的ngrx订阅
上一篇:Angular-如何根據條件使用Dragula服務拖放
下一篇:基于子組件的角度顯示/隱藏父組件
