Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  188] [ 1]  / answers: 1 / hits: 17428  / 6 Years ago, tue, august 14, 2018, 12:00:00

I have an Angular 6 app that has an export to CSV button that when clicked, runs a method on the component that generates the CSV text to be downloaded. The file is then downloaded with the following code:



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


How would I unit test clicking the Export to CSV button without triggering an actual download?



Would the only approach be to create the link in the HTML (not dynamically) and then have a Jasmine spy on the click event of the link?


More From » angular

 Answers
22

You can use the Jasmine spy functions (spyOn, spyOnProperty, jasmine.createSpy, jasmine.createSpyObj) in combination with the and methods to spy on and mock behavior.



In this case you can mock document.createElement() to return a spy object that you can use to verify that the correct properties get set and click() gets called.



Here is a working example:






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,Namen1,abcn2,defn';
}

}





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

});

[#53734] Thursday, August 9, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
martin

Total Points: 405
Total Questions: 93
Total Answers: 93

Location: Mexico
Member since Sun, Jul 25, 2021
3 Years ago
;