shlink-web-client/test/servers/services/ServersExporter.test.js

103 lines
2.7 KiB
JavaScript
Raw Normal View History

import ServersExporter from '../../../src/servers/services/ServersExporter';
2018-08-24 11:13:55 +03:00
describe('ServersExporter', () => {
const createLinkMock = () => ({
setAttribute: jest.fn(),
click: jest.fn(),
2018-08-24 11:13:55 +03:00
style: {},
});
const createWindowMock = (isIe10 = true) => ({
navigator: {
msSaveBlob: isIe10 ? jest.fn() : undefined,
2018-08-24 11:13:55 +03:00
},
document: {
createElement: jest.fn(() => createLinkMock()),
2018-08-24 11:13:55 +03:00
body: {
appendChild: jest.fn(),
removeChild: jest.fn(),
2018-08-24 11:13:55 +03:00
},
},
2018-08-24 11:13:55 +03:00
});
const serversServiceMock = {
listServers: jest.fn(() => ({
2018-08-24 11:13:55 +03:00
abc123: {
id: 'abc123',
name: 'foo',
},
def456: {
id: 'def456',
name: 'bar',
},
})),
2018-08-24 11:13:55 +03:00
};
const createCsvjsonMock = (throwError = false) => ({
toCSV: jest.fn(() => {
if (throwError) {
throw new Error('');
}
return '';
}),
2018-08-24 11:13:55 +03:00
});
describe('exportServers', () => {
let originalConsole;
beforeEach(() => {
originalConsole = global.console;
global.console = { error: jest.fn() };
global.Blob = class Blob {};
2018-08-24 11:13:55 +03:00
global.URL = { createObjectURL: () => '' };
serversServiceMock.listServers.mockReset();
2018-08-24 11:13:55 +03:00
});
afterEach(() => {
global.console = originalConsole;
});
2018-08-24 11:13:55 +03:00
it('logs an error if something fails', () => {
const csvjsonMock = createCsvjsonMock(true);
const exporter = new ServersExporter(
serversServiceMock,
createWindowMock(),
csvjsonMock,
);
exporter.exportServers();
expect(global.console.error).toHaveBeenCalledTimes(1);
expect(csvjsonMock.toCSV).toHaveBeenCalledTimes(1);
2018-08-24 11:13:55 +03:00
});
it('makes use of msSaveBlob API when available', () => {
const windowMock = createWindowMock();
const exporter = new ServersExporter(
serversServiceMock,
windowMock,
createCsvjsonMock(),
);
exporter.exportServers();
expect(serversServiceMock.listServers).toHaveBeenCalledTimes(1);
expect(windowMock.navigator.msSaveBlob).toHaveBeenCalledTimes(1);
expect(windowMock.document.createElement).not.toHaveBeenCalled();
2018-08-24 11:13:55 +03:00
});
it('makes use of download link API when available', () => {
const windowMock = createWindowMock(false);
const exporter = new ServersExporter(
serversServiceMock,
windowMock,
createCsvjsonMock(),
);
exporter.exportServers();
expect(serversServiceMock.listServers).toHaveBeenCalledTimes(1);
expect(windowMock.document.createElement).toHaveBeenCalledTimes(1);
expect(windowMock.document.body.appendChild).toHaveBeenCalledTimes(1);
expect(windowMock.document.body.removeChild).toHaveBeenCalledTimes(1);
2018-08-24 11:13:55 +03:00
});
});
});