feat: Add support for mocking fs

This commit is contained in:
Joachim Van Herwegen 2020-09-28 14:49:23 +02:00
parent 006f7ea7aa
commit e00cb05dc3
3 changed files with 180 additions and 1 deletions

View File

@ -16,7 +16,8 @@ module.exports = {
"setupFilesAfterEnv": ["jest-rdf"],
"collectCoverage": true,
"coveragePathIgnorePatterns": [
"/node_modules/"
"/node_modules/",
"/test/"
],
"coverageThreshold": {
"./src": {

View File

@ -0,0 +1,44 @@
/**
* Interface for Node.js System errors
*
* Node.js generates system errors when exceptions occur within its runtime environment.
* These usually occur when an application violates an operating system constraint.
* For example, a system error will occur if an application attempts to read a file that does not exist.
*/
export interface SystemError extends Error {
/**
* If present, the address to which a network connection failed.
*/
address?: string;
/**
* The string error code.
* Full list: https://man7.org/linux/man-pages/man3/errno.3.html
*/
code: string;
/**
* If present, the file path destination when reporting a file system error.
*/
dest?: string;
/**
* The system-provided error number.
*/
errno: number | string;
/**
* If present, extra details about the error condition.
*/
info?: any;
/**
* If present, the file path when reporting a file system error.
*/
path?: string;
/**
* If present, the network connection port that is not available.
*/
port?: string;
/**
* The name of the system call that triggered the error.
*/
syscall: string;
}
export const isSystemError = (error: any): error is SystemError => error.code && error.syscall;

View File

@ -1,10 +1,13 @@
import { EventEmitter } from 'events';
import type { Stats } from 'fs';
import type { IncomingHttpHeaders } from 'http';
import { PassThrough } from 'stream';
import type { MockResponse } from 'node-mocks-http';
import { createResponse } from 'node-mocks-http';
import streamifyArray from 'streamify-array';
import type { HttpHandler } from '../../src/server/HttpHandler';
import type { HttpRequest } from '../../src/server/HttpRequest';
import type { SystemError } from '../../src/util/errors/SystemError';
export const call = async(
handler: HttpHandler,
@ -34,3 +37,134 @@ export const call = async(
return response;
};
/**
* Mocks (some) functions of the fs system library.
* It is important that you call `jest.mock('fs');` in your test file before calling this!!!
*
* This function will return an object of which the `data` field corresponds to the contents of the root folder.
* The file system can be "reset" by assigning an empty object (`{}`) to the data field.
*
* Only files and directories are supported.
* Files are stored as strings, directories as objects with the keys corresponding to its contents.
* File path `/folder/folder2/file` will correspond to `data['folder']['folder2']['file']`.
* This can both be used to check if a file/directory was created,
* or to specify in advance certain files on the "file system".
*
* Data streams will be converted to strings for files by concatenating the contents.
*
* @param rootFilepath - The name of the root folder in which fs will start.
* @param time - The date object to use for time functions (currently only mtime from lstats)
*/
export const mockFs = (rootFilepath?: string, time?: Date): { data: any } => {
const cache: { data: any } = { data: {}};
rootFilepath = rootFilepath ?? 'folder';
time = time ?? new Date();
// eslint-disable-next-line unicorn/consistent-function-scoping
const throwSystemError = (code: string): void => {
const error = new Error('error') as SystemError;
error.code = code;
error.syscall = 'this exists for isSystemError';
throw error;
};
const getFolder = (path: string): { folder: any; name: string } => {
let parts = path.slice(rootFilepath!.length).split('/').filter((part): boolean => part.length > 0);
if (parts.length === 0) {
return { folder: cache, name: 'data' };
}
const name = parts.slice(-1)[0];
parts = parts.slice(0, -1);
let folder = cache.data;
parts.forEach((part): any => {
if (typeof folder === 'string') {
throwSystemError('ENOTDIR');
}
folder = folder[part];
if (!folder) {
throwSystemError('ENOENT');
}
});
return { folder, name };
};
const mock = {
createReadStream(path: string): any {
const { folder, name } = getFolder(path);
return streamifyArray([ folder[name] ]);
},
createWriteStream(path: string): any {
const { folder, name } = getFolder(path);
folder[name] = '';
const stream = new PassThrough();
stream.on('data', (data): any => {
folder[name] += data;
});
stream.on('end', (): any => stream.emit('finish'));
return stream;
},
promises: {
lstat(path: string): Stats {
const { folder, name } = getFolder(path);
if (!folder[name]) {
throwSystemError('ENOENT');
}
return {
isFile: (): boolean => typeof folder[name] === 'string',
isDirectory: (): boolean => typeof folder[name] === 'object',
size: typeof folder[name] === 'string' ? folder[name].length : 0,
mtime: time,
} as Stats;
},
unlink(path: string): void {
const { folder, name } = getFolder(path);
if (!folder[name]) {
throwSystemError('ENOENT');
}
if (!this.lstat(path).isFile()) {
throwSystemError('EISDIR');
}
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete folder[name];
},
rmdir(path: string): void {
const { folder, name } = getFolder(path);
if (!folder[name]) {
throwSystemError('ENOENT');
}
if (Object.keys(folder[name]).length > 0) {
throwSystemError('ENOTEMPTY');
}
if (!this.lstat(path).isDirectory()) {
throwSystemError('ENOTDIR');
}
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete folder[name];
},
readdir(path: string): string[] {
const { folder, name } = getFolder(path);
if (!folder[name]) {
throwSystemError('ENOENT');
}
return Object.keys(folder[name]);
},
mkdir(path: string): void {
const { folder, name } = getFolder(path);
if (folder[name]) {
throwSystemError('EEXIST');
}
folder[name] = {};
},
},
};
const fs = jest.requireMock('fs');
Object.assign(fs, mock);
return cache;
};