我正在尝试使用hasonCloseClose来测试sweetalert。
我模拟了sweetalert spyOn(Swal,“ fire”),它将不会调用onAfterClose。我应该设置spyOn吗?
示例.ts
testFunction(value) {
if (!value) {
Swal.fire({ type: 'success', title: 'Success', text: 'Success', onAfterClose: () => {
// call function
this.clearAll();
...
}
}
spec.ts示例
describe('test function', () => {
it('should call clearAll when call testFunction and close sweetalert', () => {
spyOn(Swal,"fire");
component.testFunction(false);
// Swal.close();
// expect(component.clearAll).toHaveBeenCall();
})
})
我要测试 Expect(component.clearAll).toHaveBeenCalled();
答案 0 :(得分:0)
默认情况下,间谍程序不返回任何值或不运行任何内容,因此请使其返回/运行与函数签名匹配的内容。您将需要自己触发回调。试试这个:
spyOn(Swal,"fire").and.callFake(args => { args.onAfterClose(); });
component.testFunction(false);
expect(component.clearAll).toHaveBeenCalled();
答案 1 :(得分:0)
您需要calSwal.clickConfirm()以编程方式单击“确认”按钮,然后将期望值放入setTimeout。
deleteLocalItems(itemId) {
Swal({
titleText: 'Are you sure to delete item?',
confirmButtonText: 'Yes',
cancelButtonText: 'No',
showCancelButton: true
}).then((result) => {
if (result.value !== undefined && result.value) {
const item = this.items.find(i => i.id === itemId);
this.items.splice(this.items.indexOf(item), 1);
}
});
}
可以测试为
it('should delete item on confirmation', (done) => {
component.items = [
{ id: '1001', name: 'Product 1'},
{ id: '1002', name: 'Product 2'},
{ id: '1003', name: 'Product 3'},
{ id: '1004', name: 'Product 4'}];
component.deleteLocalItems('1003');
expect(Swal.isVisible()).toBeTruthy();
expect(Swal.getTitle().textContent).toEqual('Are you sure to delete item?');
Swal.clickConfirm();
setTimeout(() => {
expect(component.items.length).toEqual(3);
done();
});
});