我是以下代碼的單元測驗用例。我已經提到了 component 和 component.ts.spec 檔案。
組件代碼。
this.commonService.postdata('users', request).subscribe((users: any[]) => {
users.forEach((data) => {
this.usersList.push({ name: data['firstName'] ' ' data['lastName'], id:
data['id'] });
}
} });
我在用戶時遇到問題,請參閱下面的代碼 spec.ts 檔案
Spec.ts 檔案代碼
class MockCommonService {
postdata() {
return of();
}
}
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyViewComponent>;
let commonService: CommonService;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HttpClientTestingModule, RouterTestingModule, HttpClientModule],
declarations: [MyComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers: [ { provide: CommonService, useValue: new MockCommonService() }]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyViewComponent);
commonService = TestBed.inject(CommonService);
component = fixture.componentInstance;
fixture.detectChanges();
});
}
it('list', () => {
const x = spyOn(component, 'list').and.callThrough();
const req = {
"groupnm": ['21'],
"grouptp": "ABC",
};
spyOn(commonService, 'postdata').and.returnValue(of(req));
component.list();
expect(x).toHaveBeenCalled();
});
我已經寫了上面的代碼但面臨問題。在 Angular 單元測驗用例中非常新,所以請建議正確的代碼。我在這里做錯了什么?
提前致謝。
uj5u.com熱心網友回復:
users.forEach不是函式,因為users不是陣列。在您的測驗中,const req物件不是陣列,而是在組件代碼中 postdata 回傳 observable<array>。
在測驗中應該是 const req = [some array]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/359935.html
上一篇:測驗時出現java.lang.UnsupportedOperationException
下一篇:testEnv.firestore.makeDocumentSnapshot(data,path)沒有創建新檔案
