Unable to mock `fs`
rozele opened this issue · 4 comments
From my TypeScript class, I call:
import * as fs from "fs";
...
fs.writeFileSync(...);
In my tests, I call:
import * as fs from "fs";
import { ImportMock } from "ts-mock-imports";
...
ImportMock.mockFunction(fs, "writeFileSync");
When the test runs, the fs.writeFileSync
function is not mocked.
The way you are importing fs
into your TypeScript class is incompatible with the ImportMock
way of mocking out dependencies. ImportMock
uses the module object as a stable point of reference in order to swap out real dependencies for fake dependencies. Instead of importing the entire module object into your class, instead directly import the functions you are using.
In your TypeScript class:
import { writeFileSync } from 'fs';
...
writeFileSync(...);
Now your test above should work as expected
It's strange, because ts-mock-imports
seems to work as expected for other modules that I mock that also use import * as foo from "foo"
.
The other strange thing is your fix only seems to work if I run tests using mocha, but not ts-mocha.