fix(node-utils): add path tests to writeFile

This commit is contained in:
Sam Tolmay 2020-10-23 13:35:11 +02:00
parent d01c36b1e4
commit 8bb51c383c
2 changed files with 22 additions and 20 deletions

View File

@ -17,11 +17,22 @@
import fs from 'fs';
import path from 'path';
import { promisify } from 'util';
import { type } from '@lowdefy/helpers';
const mkdirPromise = promisify(fs.mkdir);
const writeFilePromise = promisify(fs.writeFile);
async function writeFile({ filePath, content }) {
if (!type.isString(filePath)) {
throw new Error(
`Could not write file, file path should be a string, received ${JSON.stringify(filePath)}.`
);
}
if (filePath !== path.resolve(filePath)) {
throw new Error(
`Could not write file, file path was not resolved, received ${JSON.stringify(filePath)}.`
);
}
try {
await writeFilePromise(filePath, content);
} catch (error) {

View File

@ -58,25 +58,16 @@ test('writeFile should create directories if they do not exist', async () => {
await new Promise((resolve) => rimraf(testBaseDir, resolve));
});
test('writeFile error', async () => {
const filePath = path.resolve(baseDir, 'writeFileError.txt');
try {
fs.unlinkSync(filePath);
} catch (error) {
//pass
}
expect(fs.existsSync(filePath)).toBe(false);
await expect(
writeFile({
filePath,
content: { key: 'value' },
})
).rejects.toThrow(
'The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of Object'
test('readFile error id filepath is not a string', async () => {
await expect(writeFile({ filePath: true, content: `Test Write File` })).rejects.toThrow(
'Could not write file, file path should be a string, received true.'
);
});
test('readFile errors if path is not already resolved', async () => {
await expect(
writeFile({ filePath: './writeFile/writeFile.txt', content: `Test Write File` })
).rejects.toThrow(
'Could not write file, file path was not resolved, received "./writeFile/writeFile.txt".'
);
try {
fs.unlinkSync(filePath);
} catch (error) {
//pass
}
});