question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Mock implementation not working

See original GitHub issue

Do you want to request a feature or report a bug?

A bug, maybe?

What is the current behavior?

I’m trying to have multiple implementations of a mock to test different cases, but I’m not having success.

Consider the following snippet (parts omitted for brevity):

import { initRealm, startQueue } from '@/lib/realm'

class Main extends React.PureComponent {
  async componentDidMount() {
    await initRealm()
  }
}

And the test:

import React from 'react'

import { shallow } from 'enzyme'
import { initRealm } from '@/lib/realm'

import Main from './'

jest.mock('@/lib/realm', () => ({
  initRealm: jest.fn(),
})

describe('Main', () => {
  it('should successfully start realm', () => {
    initRealm.mockImplementation(() => Promise.resolve(true))
    const wrapper = shallow(<Main />)
  })

  it('should fail to init realm', () => {
    initRealm.mockImplementation(() => Promise.reject(new Error('failed to start realm')))
    const wrapper = shallow(<Main />)
  })
})

What is the expected behavior?

The mock implementation function to replace the jest.fn, so that the exception is thrown. But, instead, the test succeeds. I want to have multiple implementations of my mock so I can test both successful and fail cases.

Please provide your exact Jest configuration

"jest": {
  "preset": "react-native",
  "collectCoverage": true,
  "coverageDirectory": "./__coverage__",
  "coverageReporters": [
    "lcov"
  ],
  "collectCoverageFrom": [
    "src/**/*.{js,jsx,mjs}"
  ],
  "setupFiles": [
    "./__setup__"
  ],
  "transformIgnorePatterns": [
    "node_modules/(?!(jest-)?react-native|react-navigation)"
  ]
}
Environment:
  OS: Linux 4.13
  Node: 9.11.1
  Yarn: 1.5.1
  npm: 5.6.0
  Watchman: Not Found
  Xcode: N/A
  Android Studio: 3.0 AI-171.4443003

Am I missing something?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:12
  • Comments:8

github_iconTop GitHub Comments

3reactions
zaguiinicommented, Apr 11, 2018

If I do that way:

jest.mock('@/lib/realm')

initRealm.mockImplementationOnce(() => Promise.resolve('works'))
initRealm.mockImplementationOnce(() => Promise.reject(new Error('error thrown')))

describe('Main', () => {
  ...

It works. Why? And why it doesn’t work inside the test?

Also: will Jest respect the order that the tests are defined in the describe clause, so these tests will not be flaky?

1reaction
bcasscommented, Oct 28, 2019

I was having this issue when I was assigning the mocked method with someObj.mockedMethod = jest.fn().mockReturnValue(someVal) inside a data-driven test (using test.each). Calling someObj.mockedMethod.mockReset() at the end of the test (before recreating the mock in the next test run) fixed this issue for me.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Mock.mockImplementation() not working - Stack Overflow
And I am trying to provide a mock implementation for this. If I use something like this: jest.mock('./Service', () => { ... my...
Read more >
Common Issues - Code Your Greens
Troublshooting some of the common issues when mocking. ... You can use an ordinary function as a mocked implementation, but it's more limited...
Read more >
How to fix mockImplementation() not working in Jest?
To fix mockImplementation() not working in Jest, we should call jest.mock with a function that returns an object with the mocks.
Read more >
Mock Functions · Jest
mockFn.mockImplementation(fn) # ... Accepts a function that should be used as the implementation of the mock. The mock itself will still record all...
Read more >
Mock.mockImplementation() not working - iTecNote
Mock.mockImplementation() not working ... class Service { } export default new Service();. And I am trying to provide a mock implementation for this....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found