I wanted to be able to override third party dependencies in some TypeScript repositories and feed my code mocked dependencies for unit testing.
Let's say we've got a TS module like
import * as moment from 'moment';
export class Calendar {
public now(): void {
let now = moment().format('LLLL');
}
}
This is our Calendar class which has a dependency on MomentJS.
I want to make some unit tests, but not actually call MomentJS, because I want to check I'm passing the right values in.
Luckily, Typescript supports overriding module imports.
tsconfig.json
{
"compilerOptions": {
"paths": {
"moment": ["test/mock-modules/moment"],
}
}
}
The TypeScript documentation gives great examples.
In this example, I'm remapping to a module which is test/mock-modules/moment
relative to baseUrl
in tsconfig.json.
Since TypeScript doesn't remap imports, we need to add an alias to WebPack config:
resolve: {
alias: {
"moment": "../test/mock-modules/moment"
}
}
Hopefully this helps someone.