Мне нужна помощь, я не знаю, как смоделировать обещание и проверить, вызывается ли метод after в функции then ().
Мой код выглядит следующим образом, когда я нажимаю на кнопку сохранения в моей форме:
// File : myComponent.ts
save() {
const myObject = new MyObject({field: this.form.value.field});
this.myService.saveObject(myObject).then(() => { // I'd like to mock this
this.closeDialog(true);
}, error => {
this.otherFunction(error);
});
}
// File : myService.ts
saveOject(myObject: MyObject): Promise<any> {
return this.myApi.save(myOject).toPromise().then(res => res);
}
// File : myApi.ts
save(myObject: MyObject) {
return this.http.post('url, myObject);
}
Я пытаюсь протестировать эту функцию, и я хотел бы посмеяться (или заглушка? Я не знаю разницы) функция saveObject, когда обещание разрешается, а дело в том, что это не так.
Мой тестовый файл на актуэле выглядит так:
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
let myService: MyService;
beforeEach(async (() => {
TestBed.configureTestingModule(
).compileComponents();
myService = TestBed.inject(MyService);
}
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
spyOn(myService, 'saveOject').and.returnValue(new Promise(resolve => resolve()));
});
it('should call closeDialog method when save form is successful', () => {
const spyCloseDialog = jest.spyOn(component, 'closeDialog');
component.save();
fixture.detectChanges(); // It's a test, I don't know if it's useful
expect(spyCloseDialog).toHaveBeenCalledTimes(1); // It's 0 because I don't know how to be in the then part of my function
});
}
Кто-нибудь может мне помочь? С уважением