Reputation: 14328
I have some non-exported functions I want to test in jest. In JavaScript, I'd use rewire. In order to test TypeScript using rewire, you point your rewire()
call at the emitted JavaScript file rather than the TypeScript file.
However, I'm using webpack to compile my TS, so in my tsconfig.json, I have { compilerOptions: { noEmit: true } }
, and there is no emitted file to point rewire at.
How can I test my non-exported functions?
Upvotes: 1
Views: 715
Reputation: 14328
I came up with a less-than-ideal but better-than-exporting workaround.
jest.config.js
module.exports = {
// ...
globals: {
TEST: true,
// ...
}
};
global.d.ts
export {};
declare global {
const TEST: boolean;
// ...
}
webpack.config.js
const { DefinePlugin } = require('webpack');
module.exports = {
// ...
plugins: [
new DefinePlugin({ TEST: 'false' })
]
};
my-module.ts
function myNonExportedFunction() {
// ...
}
if (TEST) {
module.exports.myNonExportedFunction = myNonExportedFunction;
}
__tests__/module.ts
const { myNonExportedFunction } = require('../my-module');
test('myNonExportedFunction', () => {
// ...
});
The two drawbacks to this method are:
you're including minimal test code in your production code (though webpack can remove code based on constants)
you lose strong typing on your non-exported functions, though you lose that type-safety with rewire anyway
Upvotes: 1