'How do you mock FileSystem.cacheDirectory in jest?
I am trying to test a service that uses expo-file-system. Specifically I just want to mock out FileSystem.cacheDirectory since that's the first instance of my code that uses FileSystem.
I tried __mocks__/expo-file-system.ts
export default {
cacheDirectory: jest.fn(() => "<cache>/"),
};
And
jest.mock("expo-file-system", () => {
return jest.fn().mockImplementation(() => {
return {
cacheDirectory: jest.fn(() => "<cache>/"),
};
});
});
My test I think looks simple enough
import * as FileSystem from "expo-file-system";
// This part I tried commenting out
jest.mock("expo-file-system", () => {
return jest.fn().mockImplementation(() => {
return {
cacheDirectory: jest.fn(() => "<cache>/"),
};
});
});
it("verify mock", () => {
expect(FileSystem.cacheDirectory).toBe("<cache>/");
});
But I always get FileSystem.cacheDirectory as undefined
I also have the jest-expo dependency and preset.
This is a simple scenario compared to Why doesn't expo-file-system work in Jest?
Solution 1:[1]
If you look in node_modules\jest-expo\src\preset\setup.js you can find the jest.mock("expo-file-system", () => ({...})); call.
Notice that cacheDirectory property is not included in the mock, which is why it is undefined when the tests are run.
I don't know how to get the current mock set for a module in jest (ie. as we often see with ...jest.requireActual(...)), so if you want to give cacheDirectory a value, the best solution I see is to copy\paste the entire jest.mock(...) call to your test file and add cacheDirectory to the mocked module prior to running your tests.
ie.
jest.mock('expo-file-system', () => ({
downloadAsync: jest.fn(() => Promise.resolve({ md5: 'md5', uri: 'uri' })),
getInfoAsync: jest.fn(() => Promise.resolve({ exists: true, md5: 'md5', uri: 'uri' })),
readAsStringAsync: jest.fn(() => Promise.resolve()),
writeAsStringAsync: jest.fn(() => Promise.resolve()),
deleteAsync: jest.fn(() => Promise.resolve()),
moveAsync: jest.fn(() => Promise.resolve()),
copyAsync: jest.fn(() => Promise.resolve()),
makeDirectoryAsync: jest.fn(() => Promise.resolve()),
readDirectoryAsync: jest.fn(() => Promise.resolve()),
createDownloadResumable: jest.fn(() => Promise.resolve()),
cacheDirectory: "file:///test-directory/",
}));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cchapin |
