mockable-ts-commonjs

0.0.4 • Public • Published

MOCKABLE TS COMMONJS

This project will allow you to mock readonly modules generated by tsc.

Example

Given the file test.ts

export function test() {
  return true;
}

And index.ts

export * from './test.ts';

In the transpiled files tsc will create, index.js will have a read only property called test that will be the function test declared in test.js. As it is readonly, you can't mock it at all. This library simply intercept the creation os readonly properties and, if the informed parameters matches the ones generated by typescript automatically when transpiling to module commonjs, then the property exported variable will be made writable. This will allow the mocking of such exporting.

Why?

Mocking is an essential part of unit test and some feature should be supported natively in typescript for it. Unfortunately, the TypeScript team denies to do, so. So we don't have other option than workaround the transpiler ourselves!

How to install

npm i mockable-ts-commonjs --save-dev

How to use

Use this as the first line to run before all your tests

import 'mockable-ts-commonjs';

Or, if you're using mocha, put this library in the property require of .mocharc, like this:

{
  ...
  "require": ["@codibre/confs/ts-node-register.js", 'mockable-ts-commonjs']
  ...
}

Notice that, in the above example, we also use a ts-node register so we can better run our ts tests, but it's not required for mockable-ts-commonjs to work.

License

Licensed under MIT.

Package Sidebar

Install

npm i mockable-ts-commonjs

Weekly Downloads

64

Version

0.0.4

License

MIT

Unpacked Size

11.7 kB

Total Files

5

Last publish

Collaborators

  • farenheith