Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Node filesystem spies and mocks

NotificationsYou must be signed in to change notification settings

streamich/spyfs

Repository files navigation

Spy on filesystem calls. Create file system mocks. Use for testing.

Install:

npm install --save spyfs

Create 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=>{// ...});

Want to spy on real filesystem?

Overwrite the realfs module usingfs-monkey to spy on all filesystemcalls:

import{patchFs}from'fs-monkey';patchFs(sfs);

Useasync/await

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',()=>{});

Action properties

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('/');

Subscribe to events

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);

Mock responses

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!"));});

Sync mocking

action.resolve(result)

Returns to the userresult as successfully executed action, belowall operationsreadFileSync will return'123':

sfs.on('readFileSync',action=>{action.resolve('123');});

action.reject(error)

Throwserror:

sfs.on('statSync',action=>{action.reject(newError('This filesystem does not support stat'));});

action.exec()

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'));});

action.result

result is a reference to theaction for your convenience:

Async mocking

Just like sync mocking actions supportresolve,reject andexec methods,but, in addition, async mocking also haspause andunpause methods.

action.resolve(results)

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']);});

action.reject(error)

Fails filesystem call and returns your specified error.

sfs.on('readFile',({reject})=>{reject(newError('You cannot touch this file!'));});

action.pause()

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.

action.unpause()

Un-pauses previously pauses filesystem operation:

sfs.on('readFile',({pause, unpause})=>{// This effectively does nothing:pause();unpause();});

action.exec()

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();}});

action.result

result is a reference to theaction for your convenience:

Spy constructor

Create spying filesystems manually:

import{Spy}from'spyfs';

new Spy(fs[, listener])

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.

sfs.subscribe(listener)

Subscribe to all filesystem actions:

constsfs=newSpy(fs);sfs.subscribe(action=>{});

It is equivalent to callingsfs.on('action', listener).

sfs.unsubscribe(listener)

Unsubscribes your listener. It is equivalent to callingsfs.off('action', listener).

sfs.on(method, listener)

Subscribes to a specific filesystem call.

sfs.on('readFile',listener);

sfs.off(method, listener)

Unsubscribes from a specific filesystem call.

License

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

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors3

  •  
  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp