I'm using Chai
, Mocha
for testing in my project. I want to test the createTreefromFolder function from a module tree.js
:
export function createTreefromFolder(path: string): string[] {
const files = listFilesFromFolder(path);
const tree: string[] = [createFirstBranch(path)];
files.forEach((file) => {
tree.push(Prefix.VERTICAL.concat(file));
});
return tree;
}
My goal is to mock listFilesFromFolder
function in my test in order to return a specific value.
In the tests folder I have:
it("creation of a unique folder tree", () => {
const expectedArray: string[] = ["🗃️ empty_folder"];
mock("src.tree.listFilesFromFolder").return_value = ["empty_folder"] // mock here
expect(createTreefromFolder(empty_test_folder_path)).to.eql(expectedArray);
});
Is there a way to do that as python do that with unitest.mock.patch ?
One way is to pass listFilesFromFolder
as a parameter for createTreefromFolder
.
Another one -- to use some king of dependency injection, and mock listFilesFromFolder dependency inside your registry.
There's no way to patch function source code from outside as far as I know. So functionality you wanna mock should be initially imported from a mockable place, dependency container (IoC container) of some kind.