我正在學習如何撰寫單元測驗。這是課程中的部分代碼。
#spec.ts
...
beforeEach(waitForAsync(() => {
const coursesServiceSpy = jasmine.createSpyObj("CoursesService", [
"findAllCourses",
]);
TestBed.configureTestingModule({
imports: [CoursesModule, NoopAnimationsModule, HttpClientTestingModule],
providers: [{ provide: CoursesService, useValue: coursesServiceSpy }],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
el = fixture.debugElement;
coursesService = TestBed.inject(CoursesService);
});
}));
...
it("should display data from service", () => {
coursesService.findAllCourses.and.returnValue(of(fake data));
fixture.detectChanges();
// the test code
});
#component.ts
reloadCourses() {
const courses$ = this.coursesService.findAllCourses();
}
問題是我正在使用組件存盤來管理呼叫效果后不回傳任何內容的狀態。
# my component
constructor(
private store: StoreService
) {}
...
viewModel$ = this.store.viewModel$;
// how I call effect to refresh data
this.store.initCourses();
我只是直接在我的模板中顯示來自組件存盤的資料。
# my template
<ng-container *ngIf="viewModel$ | async as viewModel">
我不知道如何偽造組件存盤回應并讓我的組件知道發生了一些變化。我想要做的是為viewModel$Observable 賦值。有誰知道如何做到這一點或有任何其他解決方案?
抱歉我的解釋不好,如果您需要更多資訊,請告訴我。非常感謝!
uj5u.com熱心網友回復:
假設StoreService只是一項服務,您需要模擬它,類似于CoursesService您在課堂上的模擬方式。
你應該試試這個:
let storeServicesSpy: jasmine.SpyObj<StoreService>;
// Mock this behavior subject accordingly to how the data should be.
// Empty object is shown here.
const mockViewModel$ = new BehaviorSubject<any>({});
beforeEach(waitForAsync(() => {
// Create a spy object
// The first string argument is optional and used for debugging purposes.
// The second array argument is an array of strings of public methods you would
// like to be mocked.
// The third object argument are instance variables you would like to mock
storeServiceSpy = jasmine.createSpyObj<StoreService>('StoreService', ['initCourses'], { viewModel$: mockViewModel$ });
}));
TestBed.configureTestingModule({
...
// Assign our mock for when the component asks for the StoreService
providers: [{ provide: StoreService, useValue: storeServiceSpy }],
...
}).compileComponents();
然后您可以使用新資料mockViewModel$.next({/* new stuff here */ });進行viewModel$發射。
在此處了解有關測驗的更多資訊:https ://testing-angular.com/testing-components-depending-on-services/#testing-components-depending-on-services 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/523259.html
上一篇:為python程式撰寫測驗
