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

[Bug]: mocking a function which is dereferenced using require syntax doesnt get mocked #15017

Open
mehhdiii opened this issue Apr 7, 2024 · 1 comment

Comments

@mehhdiii
Copy link

mehhdiii commented Apr 7, 2024

Version

29.7.0

Steps to reproduce

  1. Suppose you have a function foo used in example.ts:
const {foo} = require('./path-to-func');

export const bar = () => {
    ...
    foo()
}

  1. Now suppose your test file for example.ts looks like the following:
const example = require('path-to-example');
const funcs = require('./path-to-func')

describe('example test', () => 
{
    it('should call mocked foo()', () => {
        jest.spyOn(funcs, foo')
      .mockImplementation(() => console.log('mock called!'));
       
       //call bar(): 
       example.bar()
    })
}
)

Expected behavior

Mocked foo should be called.

Actual behavior

it calls the original foo instead of using the mocked foo.

Additional context

We can resolve this if we dont deference the require statement (in example.ts):

//example.ts
const funcs = require('./path-to-func');
export const bar = () => {
    ...
    funcs.foo()
}

Environment

System:
    OS: Linux 6.5 Ubuntu 22.04.3 LTS 22.04.3 LTS (Jammy Jellyfish)
    CPU: (20) x64 12th Gen Intel(R) Core(TM) i7-12800H
  Binaries:
    Node: 18.17.1 - ~/.nvm/versions/node/v18.17.1/bin/node
    npm: 9.6.7 - ~/.nvm/versions/node/v18.17.1/bin/npm
Copy link

github-actions bot commented May 7, 2024

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 30 days.

@github-actions github-actions bot added the Stale label May 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant