0

I am having trouble figuring out how to mock an async method that is called from the mounted lifecycle method. I am trying to mock UsersApi.getAllUsers().

//code.vue
mounted: async function () {
  await UsersApi.getAllUsers().then(response => {
    this.options = response.data
  })
}

//code.test.js
import UsersApi from '@/api/users'
…
jest.mock('UsersApi')
UsersApi.getAllUsers.mockResolvedValue([
  {
    user_id: 123,
    first_name: 'Abc',
    last_name: 'Def'
  }
])
…

Output: Cannot find module 'UsersApi' from 'code.spec.js'

The module exists and is being used in the component. Perhaps using a mock is not appropriate for this purpose?

Another option would be to somehow suppress the mounted method, which would work because I am setting this.options from the test anyway.

Edit: this is where getAllUsers is coming from.

//users.js
export default {
  async getAllUsers() {
    …
  },
  async getUsers(payload) {
    …
  }
…
Stephen
  • 155
  • 2
  • 11
  • 1
    `jest.mock` takes a *path* to the module, see e.g. https://jestjs.io/docs/en/jest-object#jestmockmodulename-factory-options. – jonrsharpe Oct 28 '20 at 21:41
  • Thank you! I've updated my original post with what `users.js` looks like. I think that is going to complicate things. – Stephen Oct 28 '20 at 22:20
  • 1
    It doesn't really matter what's in that file, the point is that the Jest mocking method takes *the path to the module*, the same thing you'd `import whatever from "this/path/here"`, not `"whatever"` name you happen to have assigned the result to. – jonrsharpe Oct 28 '20 at 22:22
  • Great, thanks for the help. – Stephen Oct 28 '20 at 22:26
  • Now I get `TypeError: _users.default.getAllUsers.mockResolvedValue is not a function`. Do you happen to have an idea for that, @jonrsharpe? – Stephen Oct 28 '20 at 23:03
  • This project doesn't use TypeScript, so I guess I'll keep digging. Thanks. – Stephen Oct 29 '20 at 14:37
  • 1
    This got me sorted: https://stackoverflow.com/questions/61627298/jest-mockresolvedvalue-is-not-a-function I ended up calling `UsersApi.getAllUsers = jest.fn().mockResolvedValue…` – Stephen Oct 29 '20 at 14:40

0 Answers0