mirror of
https://github.com/lowdefy/lowdefy.git
synced 2025-02-17 14:30:34 +08:00
fix(node-utils): add path tests to writeFile
This commit is contained in:
parent
d01c36b1e4
commit
8bb51c383c
@ -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) {
|
||||
|
@ -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
|
||||
}
|
||||
});
|
||||
|
Loading…
Reference in New Issue
Block a user