/esmock

mock esm imported modules for unit-tests

Primary LanguageJavaScriptMIT LicenseMIT

esmock

npm version Build Status

esmock must be used with node's experimental --loader

{
  "name": "give-esmock-a-star",
  "type": "module",
  "scripts": {
    "test-ava": "ava --node-arguments=\"--loader=esmock\"",
    "test-mocha": "mocha --loader=esmock --no-warnings"
  }
}

Use it await esmock('./to/module.js', childmocks, globalmocks)

import test from 'ava';
import esmock from 'esmock';

test('should mock modules and local files at same time', async t => {
  const main = await esmock('../src/main.js', {
    stringifierpackage : o => JSON.stringify(o),
    '../src/hello.js' : {
      default : () => 'world'
    },
    '../src/util.js' : {
      exportedFunction : () => 'foobar'
    }
  });

  t.is(main(), JSON.stringify({ test : 'world foobar' }));
});

test('should do global instance mocks —third parameter', async t => {
  const { getFile } = await esmock('../src/main.js', {}, {
    fs : {
      readFileSync : () => {
        return 'anywhere the instance uses fs readFileSync';
      }
    }
  });

  t.is(getFile(), 'anywhere the instance uses fs readFileSync');
});

changelog

  • 0.3.9 May.05.2021
    • small change to README
    • added a test, update gitlab action to use node 16.x
  • 0.3.8 Apr.21.2021
    • small change to README
  • 0.3.7 Apr.20.2021
    • add test, throw error if mocked module path is not found
  • 0.3.6 Apr.19.2021
    • throw error if mocked module path is not found
  • 0.3.5 Apr.18.2021
    • added gitlab actions npm test: node 12.x, 14.x and 15.x
  • 0.3.3 Apr.13.2021
    • added keywords to package.json, use github action to npm publish
  • 0.3.1 Apr.12.2021
    • simplify README
  • 0.3.0 Apr.10.2021
    • adds support for mocking modules 'globally' for the instance
  • 0.2.0 Apr.10.2021
    • adds support for mocking core modules such as fs and path
  • 0.1.0 Apr.10.2021
    • adds support for native esm modules