I want to mock a function within the same file, this is the structure
// password.js
async function main(){
password = await getPassword();
return password;
}
async function getPassword() {
return 'thisIsMyPassword';
}
module.exports = {
main,
getPassword
}
I'm able to mock the function if I change the getPassword function from getPassword() to module.exports.getPassword() like this...
// password.js
async function main(){
password = await module.exports.getPassword();
return password;
}
async function getPassword() {
return 'thisIsMyPassword';
}
module.exports = {
main,
getPassword
}
And the test file...
const password = require('./password')
describe('Password test', () => {
afterEach(() => {
jest.restoreAllMocks();
});
test('return password', async () => {
jest.clearAllMocks();
jest.spyOn(password, 'getPassword').mockReturnValueOnce('ilovedualipa')
expect(await password.main()).toEqual('ilovedualipa');
});
});
I would like to know if there is a better way to do it because I don't know if adding "module.exports" is a good practice.