-1

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.

1 Answers1

1

A cleaner way you could do it is using an object and the this keyword:

const passObj = {
  getPassword: async function() {
    return 'thisIsMyPassword';
  },
  main: async function(){
    password = await this.getPassword();
    return password;
  }
}

module.exports = passObj;
ca1c
  • 1,111
  • 10
  • 23