vendredi 22 février 2019

Jest mock submodule function

I have this node module called client. It has the following structure:

//index.js
import users from "./users"

export default { users }

And:

//users.js
export default { getUser }
function getUser(username) {
    ...
    return {role: userRole}  
}

I want to mock this getUser(username) function in my tests. So I could call something like:

client.users.getUser.mockResolvedValueOnce({role: "manager"}) 

My test header is like:

let client = jest.genMockFromModule('client').default;
client.users.getUser = jest.fn();

But, running my test, I get the following error when my original code call client.users.getUser.

TypeError: Cannot read property 'users' of undefined

  58 | 
  59 |     // Retrieve user and then return its projects
> 60 |     client.users.getUser(username)
     |                  ^
  61 |         .then(user => {
  62 |             if (!user) {
  63 |                 throw new Error(`User ${username} not found`)

  at Object.getUser (node_modules/client/build/users.js:26:45)
  at Object.getUser [as insert] (src/web/controller/projects.js:60:18)
  at Object.insert (src/web/controller/projects.test.js:80:18)

Aucun commentaire:

Enregistrer un commentaire