如何使用onAfterClose对sweetalert进行单元测试

问题描述 投票:0回答:1

我正试图用onAfterClose来测试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();
      ...
   }
}

示例规格

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();

angular karma-jasmine
1个回答
0
投票

间谍不会返回任何值或默认情况下不运行任何内容,因此请返回/运行与函数签名匹配的内容。您需要自己触发回调。试试这个 :

spyOn(Swal,"fire").and.callFake(args => { args.onAfterClose(); });
component.testFunction(false);
expect(component.clearAll).toHaveBeenCalled();
© www.soinside.com 2019 - 2024. All rights reserved.