You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular+Ionic中用Jasmine测试html2canvas默认导出函数的Promise

解决html2canvas默认导出的Jasmine单元测试问题

正确的Spy实现方式

html2canvas采用默认导出形式,直接用spyOn(xxx, 'default')会报错,原因是default属于模块的属性而非方法,需要通过以下两种方式处理:

方法1:替换模块的默认导出属性

  1. 测试文件中以命名空间形式导入html2canvas:
import * as html2canvasModule from 'html2canvas';
  1. 创建模拟Canvas对象和Spy函数:
const mockCanvas = document.createElement('canvas');
// 按需给mockCanvas添加需要的方法,比如toDataURL
mockCanvas.toDataURL = jasmine.createSpy().and.returnValue('data:image/png;base64,mock-data');
const html2canvasSpy = jasmine.createSpy('html2canvas')
  .and.returnValue(Promise.resolve(mockCanvas));
  1. 在测试初始化阶段替换模块默认导出:
beforeEach(() => {
  // 替换默认导出为Spy函数
  (html2canvasModule as any).default = html2canvasSpy;
  
  // 初始化组件
  TestBed.configureTestingModule({
    declarations: [YourTargetComponent]
  }).compileComponents();
  fixture = TestBed.createComponent(YourTargetComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});
  1. 编写测试断言:
it('should call html2canvas and process the returned canvas', (done) => {
  // 调用组件中使用html2canvas的方法
  component.triggerHtml2canvasLogic();
  
  // 断言Spy被正确调用
  expect(html2canvasSpy).toHaveBeenCalledWith(/* 预期传入的DATA参数 */);
  
  // 处理异步Promise,确保等待回调执行完成
  html2canvasSpy.calls.mostRecent().returnValue.then(() => {
    // 断言回调中的业务逻辑,比如组件属性更新
    expect(component.processedResult).toBe('预期值');
    done();
  });
});

方法2:使用spyOnProperty监听默认导出

由于default是模块的getter属性,也可以通过spyOnProperty直接替换:

import * as html2canvas from 'html2canvas';

beforeEach(() => {
  const mockCanvas = document.createElement('canvas');
  const html2canvasSpy = jasmine.createSpy().and.returnValue(Promise.resolve(mockCanvas));
  // 监听default属性的getter,返回Spy函数
  spyOnProperty(html2canvas, 'default', 'get').and.returnValue(html2canvasSpy);
  
  // 初始化组件...
});

后续断言逻辑与方法1完全一致。

关键注意点

  • 模拟Canvas时,需根据业务代码用到的方法(如toDataURL、width等)补充对应的Mock实现;
  • 测试异步逻辑必须使用done回调或async/await,避免测试提前结束导致断言失效。

内容的提问来源于stack exchange,提问作者gazops

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 21:21:46