Commit f3136140 authored by Alejandro Celaya's avatar Alejandro Celaya Committed by Alejandro Celaya

Create function that reads an JSON-parses a File object

parent 07e786e0
import { promiseWithResolvers } from './promise-with-resolvers';
/**
* Reads and tries to JSON-parse a file
* @return - Promise that resolves to parsed content or rejects with any error
* that occurred during parsing
*/
export function readJSONFile(
file: File,
/* istanbul ignore next - test seam */
fileReader = new FileReader(),
): Promise<unknown> {
const { promise, resolve, reject } = promiseWithResolvers();
fileReader.addEventListener('loadend', (e: ProgressEvent<FileReader>) => {
try {
const content = e.target?.result?.toString() ?? '';
const parsed = JSON.parse(content);
resolve(parsed);
} catch (error) {
reject(error);
}
});
fileReader.readAsText(file);
return promise;
}
import { readJSONFile } from '../read-json-file';
describe('readJSONFile', () => {
const file = new File([], 'my-file');
function createFakeFileReader(fileContent) {
return {
addEventListener: sinon.stub().callsArgWith(1, {
target: {
result: fileContent,
},
}),
readAsText: sinon.stub(),
};
}
it('rejects when content is not valid JSON', async () => {
const fakeFileReader = createFakeFileReader('not JSON');
await assert.rejects(
readJSONFile(file, fakeFileReader),
'Unexpected token \'o\', "not JSON" is not valid JSON',
);
assert.calledWith(fakeFileReader.readAsText, file);
assert.calledWith(
fakeFileReader.addEventListener,
'loadend',
sinon.match.func,
);
});
it('resolves when content is valid JSON', async () => {
const fakeFileReader = createFakeFileReader('{ "foo": "bar" }');
const content = await readJSONFile(file, fakeFileReader);
assert.deepEqual(content, { foo: 'bar' });
assert.calledWith(fakeFileReader.readAsText, file);
assert.calledWith(
fakeFileReader.addEventListener,
'loadend',
sinon.match.func,
);
});
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment