Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jest.mock does not mock async methods in module #3135

Closed
troyschneringer opened this issue Mar 13, 2017 · 5 comments · Fixed by #3209
Closed

jest.mock does not mock async methods in module #3135

troyschneringer opened this issue Mar 13, 2017 · 5 comments · Fixed by #3209

Comments

@troyschneringer
Copy link

node: 7.6.0
os: macOS Sierra (10.12.3)

I have create a module with a method defined as async. When mocking that module in tests it does not mock the async method.

module.js

function awaitable() {
  return Promise.resolve();
}

module.exports.asyncMethod = async () => {
  await awaitable();
  return 42;
}
module.exports.syncMethod = () => {
  return 42;
}

example.test.js

jest.mock('./module');
const mod = require('./module');

describe('async module method', () =>{
  test('does not get mocked', () => {
    expect(mod.asyncMethod).toBeDefined();
    expect(mod.syncMethod).toBeDefined();
  });
});

package.json

{
  "name": "test",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "jest": "^19.0.2"
  }
}

The test fails because the asyncMethod is not defined on the mocked module.

@troyschneringer
Copy link
Author

I have worked around this by adding the following to my tests (but its obviously less that ideal):

beforeAll(() => {
  mod.asyncMethod = jest.fn();
});

@gregberge
Copy link
Contributor

+1, same problem

gregberge pushed a commit to argos-ci/argos that referenced this issue Mar 22, 2017
@thymikee
Copy link
Collaborator

Cannot repro, both tests pass in my case (I use transform-async-to-generator).

@gregberge
Copy link
Contributor

It only happens if you use the native implementation of async / await.

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 13, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants