Skip to content

Repository files navigation

modpod

Build Statuscodecov

Isolate your ES Modules for testing.

 npm i -D modpod

Easy Mode

import{test}from"node:test";importmodpodfrom"modpod";test("easy mode",async()=>{constinstance=awaitmodpod("./target.js",{"./dep.js": {// Replaces `export default function(){...}` in ./dep.jsdefault: ()=>"mocked default",// Replaces `export function otherThing(){...}` in ./dep.jsotherThing: ()=>"mocked named export 'otherThing'"}});// Exercise instance// Assert what you expected would happen});

The default export is a function that sets up a mock environment, imports the target, and cleans up.

  • modpod() is a shallow mock. It'll only replace dependencies one level deep.

  • modpod.strict() will make sure that all dependencies of ./target.js are mocked. If an import is missing a mock, an error will be thrown.

  • modpod.deep() will replace ./dep.js anywhere it is imported. Even if it's a dependency of a dependency.

Note: If a mock is declared, but never used, then an error will be thrown.

Hard Mode

If you need more control over the mock lifecycle (like dynamic imports), then you'll need to use the Pod class directly.

Let's consider a few files:

target.js

exportasyncfunctiondoSomething(){constdep=awaitimport("./dep.js");returndep();}

dep.js

exportdefault()=>"dep";

Now we can write a test that handles the dynamic import.

importassertfrom"node:assert";import{test,mock}from"node:test";import{Pod}from"modpod";test("hard mode",async(t)=>{constp=newPod({strict: true});t.after(()=>p.dispose());// Clean upconstdep=mock.fn(()=>"mocked");// NOTE: dep will be wrapped {default: dep} because it's a function.p.mock("./dep.js",dep);constinstance=awaitp.import("./target.js");assert.strictEqual(dep.mock.calls.length,0);constresult=awaitinstance.doSomething();assert.strictEqual(dep.mock.calls.length,1);});

About

Isolate your ES Modules for testing.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages