I have a TypeScript file config.ts
that will be run with node:
import myDependency = require('my-dependency');
export = {
doSomething = () => {
...
}
}
In other TypeScript file, I can import
this file with full type safety:
import config = require('./config');
config.doSomething();
config.doSomethingElse(); // compiler error, this method doesn't exist
Now I want to unit test this script. In order to mock out the dependencies that this script require()
s I'm using proxyquire, which lets me provide the values that my script will get when it makes calls to require()
. Here's what my test might look like:
import proxyquire = require('proxyquire');
const config = proxyquire('./config', {
'my-dependency': {} // this mocked object will be provided when config.ts asks for `my-dependency`
});
expect(config.doSomething()).to.do.something();
This works fine, except that my config
variable is of type any
because I'm using proxyquire()
in place of require()
. TypeScript must give the require()
function special treatment to allow it to perform module resolution. Is there a way to tell the TypeScript compiler that proxyquire()
should also do module resolution, similar to require()
?
I could rewrite config.ts
as a class or make it use an interface. Then I would be able to explicitly type the variables in my tests by importing the class/interface definition. But allowing proxyquire()
to implicitly type things for me would be far be the easier solution.