theintern / intern

A next-generation code testing stack for JavaScript.
https://theintern.io/
Other
4.36k stars 309 forks source link

Add module mocking functionality #1140

Open jason0x43 opened 4 years ago

jason0x43 commented 4 years ago

Intern should provide an out-of-the-box solution for module mocking. The system should work with at least the Node loader and webpack, and it should provide type safety.

The mocking system currently used for Intern's self tests would probably work:

({ default: Node } = await mockImport(
  () => import('src/core/lib/executors/Node'),
  replace => {
    replace(() =>
      import('src/core/lib/common/ErrorFormatter')
    ).withDefault(MockErrorFormatter as any);
    replace(() => import('src/core/lib/common/console')).with(
      mockConsole
    );
  }
);

The snippet above dynamically imports a module, replacing certain of that modules imports with mock values. These imports are type safe, which is why the as any is required for the MockErrorFormatter mock, which doesn't completely mock ErrorFormatter.

The built in mocking system should be optional, and it shouldn't get in the way if the user wants to use something else.