- Notifications
You must be signed in to change notification settings - Fork4
Node filesystem spies and mocks
streamich/spyfs
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Spy on filesystem calls. Create file system mocks. Use for testing.
Install:
npm install --save spyfsCreate a new file system that spies:
import*asfsfrom'fs';import{spy}from'spyfs';constsfs=spy(fs);
Now you can usesfs for all your filesystem operations.
constdata=sfs.readFileSync('./package.json').toString();
Subscribe to all actions happening on that filesystem:
sfs.subscribe(action=>{// ...});
Every time somebody usessfs, the subscription callback will be called.You will receive a single argument: anaction which is aPromise objectcontaining all the information about the performed filesystem operation and its result.
You can also subscribe by providing a listener at creation:
constsfs=spy(fs,action=>{// ...});
Overwrite the realfs module usingfs-monkey to spy on all filesystemcalls:
import{patchFs}from'fs-monkey';patchFs(sfs);
spyfs returnsactions which are instances of thePromise constructor,so you can useasynchronous functions for convenience:
constsfs=spy(fs,asyncfunction(action){console.log(awaitaction);// prints directory files...});sfs.readdir('/',()=>{});
Use withmemfs
You can usespyfs with anyfs-like object, includingmemfs:
import{fs}from'memfs';import{spy}from'spyfs';constsfs=spy(fs,asyncfunction(action){console.log(awaitaction);// bar});sfs.writeFile('/foo','bar',()=>{});sfs.readFile('/foo','utf8',()=>{});
spyfs actions have extra properties that tell you more about the actionbeing executed:
action.method(string) - name of filesystem method called.action.isAsync(boolean) - whether the filesystem method called was asynchronous.action.args(Array) - list of arguments with which the method was called (sans callback).
constsfs=spy(fs,action=>{console.log(action.method);// readdir, readdirSyncconsole.log(action.isAsync);// true, falseconsole.log(action.args);// [ '/' ], [ '/' ]});sfs.readdir('/',()=>{});sfs.readdirSync('/');
The returned filesystem object is also an event emitter, you can subscribeto specific filesystem actions using the.on() method, in that case youwill receive only actions for that method:
sfs.on('readdirSync',asyncfunction(action){console.log(action.args,awaitaction);});sfs.readdirSync('/');
Listening foraction event is equivalent to subscribing using.subscribe().
sfs.on('action',listener);sfs.subscribe(listener);
You can overwrite what is returned by the filesystem call at runtime or eventhrow your custom errors, this way you can mock any filesystem call:
For example, prohibitreadFileSync for/usr/foo/.bashrc file:
sfs.on('readFileSync',({args, reject})=>{if(args[0]==='/usr/foo/.bashrc')reject(newError("Cant't touch this!"));});
Returns to the userresult as successfully executed action, belowall operationsreadFileSync will return'123':
sfs.on('readFileSync',action=>{action.resolve('123');});
Throwserror:
sfs.on('statSync',action=>{action.reject(newError('This filesystem does not support stat'));});
Executes an action user was intended to perform and returns back resultonly to you. This method can throw.
sfs.on('readFileSync',action=>{constresult=action.exec();if(result.length>100)action.reject(newError('File too long'));});
result is a reference to theaction for your convenience:
Just like sync mocking actions supportresolve,reject andexec methods,but, in addition, async mocking also haspause andunpause methods.
Successfully executes user's filesystem call.results is an array, becausesome Node's async filesystem calls return more than one result.
sfs.on('readFile',({resolve})=>{resolve(['123']);});
Fails filesystem call and returns your specified error.
sfs.on('readFile',({reject})=>{reject(newError('You cannot touch this file!'));});
Pauses the async filesystem call until you un-pause it.
sfs.on('readFile',({pause})=>{pause();// The readFile operation will never end,// if you don't unpause it.});
Pausing is useful if you want to perform some other async IO before yieldingback to the original filesystem operation.
Un-pauses previously pauses filesystem operation:
sfs.on('readFile',({pause, unpause})=>{// This effectively does nothing:pause();unpause();});
Executes user's intended filesystem call and returns the result only to you.Unlike the sync versionexec, asyncexec returns a promise.
You should use it together withpause() andunpause().
sfs.on('readFile',({exec, pause, unpause, reject})=>{pause();exec().then(result=>{if(result.length<100){reject(newError('File too small'));}else{unpause();}});});
Useasync/await withexec():
sfs.on('readFile',asyncfunction({exec, pause, unpause, reject}){pause();letresult=awaitexec();if(result.length<100){reject(newError('File too small'));}else{unpause();}});
result is a reference to theaction for your convenience:
Create spying filesystems manually:
import{Spy}from'spyfs';
fs is the file system to spy on. Note thatSpy will not overwrite orin any way modify your original filesystem, but rather it will create anew object for you.
listener is an optional callback that will be set using the.subscribe()method, see below.
Subscribe to all filesystem actions:
constsfs=newSpy(fs);sfs.subscribe(action=>{});
It is equivalent to callingsfs.on('action', listener).
Unsubscribes your listener. It is equivalent to callingsfs.off('action', listener).
Subscribes to a specific filesystem call.
sfs.on('readFile',listener);
Unsubscribes from a specific filesystem call.
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, ordistribute this software, either in source code form or as a compiledbinary, for any purpose, commercial or non-commercial, and by anymeans.
In jurisdictions that recognize copyright laws, the author or authorsof this software dedicate any and all copyright interest in thesoftware to the public domain. We make this dedication for the benefitof the public at large and to the detriment of our heirs andsuccessors. We intend this dedication to be an overt act ofrelinquishment in perpetuity of all present and future rights to thissoftware under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OROTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OROTHER DEALINGS IN THE SOFTWARE.
For more information, please refer tohttp://unlicense.org/
About
Node filesystem spies and mocks
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors3
Uh oh!
There was an error while loading.Please reload this page.