When attempting to test a library function that uses the fs module, I received assistance in this question on Stack Overflow. The feedback suggested avoiding mocks for better testing, an approach I agreed with @unional.
I am now facing a similar challenge with the accessSync method, as it requires some modifications for proper testing.
After implementing the suggestions from @unional, here is my updated code:
import fs from 'fs';
export function AccessFileSync(PathAndFileName: string): boolean {
if (!PathAndFileName) {
throw new Error('Missing File Name');
}
try {
AccessFileSync.fs.accessSync(PathAndFileName, fs.constants.F_OK | fs.constants.R_OK);
} catch {
return false;
}
return true;
}
AccessFileSync.fs = fs;
To test this function, I would follow these steps:
describe('Return Mock data to test the function', () => {
it('should return the test data', () => {
// mock function
AccessFileSync.fs = {
accessSync: () => { return true; }
};
const AccessAllowed: boolean = AccessFileSync('test-path'); // Non-existent file due to mock
expect(AccessFileSync.fs.accessSync).toHaveBeenCalled();
expect(AccessAllowed).toBeTruthy();
});
});
While the initial test works, subsequent tests fail to obtain the expected results when changing parameters. For example:
describe('Return Mock data to test the function', () => {
it('should return the test data', () => {
// mock function
AccessFileSync.fs = {
accessSync: () => { return false; }
};
const AccessAllowed: boolean = AccessFileSync('test-path'); // Non-existent file due to mock
expect(AccessFileSync.fs.accessSync).toHaveBeenCalled();
expect(AccessAllowed).toBeFalsy(); // Fails to match expectation
});
});
Additionally, I aim to address tslint warnings regarding the use of "as any" and prefer the notation "Variable:type" instead.