如何使用Jasmine(Angular)单元测试下载文件?

时间:2018-08-14 16:53:48

标签: javascript angular jasmine

我有一个Angular 6应用,该应用具有“导出到CSV”按钮,单击该按钮可在组件上运行一种方法,该方法生成要下载的CSV文本。然后使用以下代码下载文件:

const tempLink = document.createElement('a');
tempLink.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvContent);
tempLink.target = '_blank';
tempLink.download = 'export.csv';
tempLink.click();

如何在不触发实际下载的情况下对单击“导出为CSV”按钮进行单元测试?

唯一的方法是在HTML中创建链接(不是动态地),然后让茉莉花间谍监视链接的click事件吗?

1 个答案:

答案 0 :(得分:2)

您可以将Jasmine spy functions(spyOn,spyOnProperty,jasmine.createSpy,jasmine.createSpyObj)与and methods结合使用来监视和模拟行为。

在这种情况下,您可以模拟document.createElement()返回一个间谍对象,该对象可用于验证是否设置了正确的属性并调用了click()

这是一个有效的示例:


example.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-example',
  template: '<div><button (click)="download()">Download Csv</button></div>'
})
export class ExampleComponent implements OnInit {

  constructor() { }

  ngOnInit() { }

  download() {
    const csvContent = this.generateCsv();
    const tempLink = document.createElement('a');
    tempLink.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvContent);
    tempLink.target = '_blank';
    tempLink.download = 'export.csv';
    tempLink.click();
  }

  private generateCsv() {
    return 'ID,Name\n1,abc\n2,def\n';
  }

}

example.component.spec.ts

import { ExampleComponent } from './example.component';

describe('ExampleComponent', () => {

  it('should download the csv file', () => {
    // create spy object with a click() method
    const spyObj = jasmine.createSpyObj('a', ['click']);
    // spy on document.createElement() and return the spy object
    spyOn(document, 'createElement').and.returnValue(spyObj);

    const comp = new ExampleComponent();
    comp.download();

    expect(document.createElement).toHaveBeenCalledTimes(1);
    expect(document.createElement).toHaveBeenCalledWith('a');

    expect(spyObj.href).toBe('data:text/csv;charset=utf-8,ID,Name%0A1,abc%0A2,def%0A');
    expect(spyObj.target).toBe('_blank');
    expect(spyObj.download).toBe('export.csv');
    expect(spyObj.click).toHaveBeenCalledTimes(1);
    expect(spyObj.click).toHaveBeenCalledWith();
  });

});