0

I'm trying to mock a function of an object with Jest and Typescript and it just does not work. Here is a short version of what I have:

// myModule.ts

export const Foo = {
  doSomething: () => {
    // ... does something
    console.log('original implementation');
  }
}

Then in my test:

jest.mock('.myModule.ts', () => {
  return {
    Foo: {
      doSomething: jest.fn().mockImplementation(() => {
        console.log('mock implementation')
      })
    }
  }
})

// .. further down in the test
Foo.doSomething();

Shouldn't the console.log('mock implementation') be called when I call Foo.doSomething()? It doesn't error and it's not calling the original implementation anymore, but it's also not calling my mockImplementation.

2 Answers 2

1

Try this:

import { Foo } from './foo';

jest
  .spyOn(Foo, 'doSomething')
  .mockImplementation(() => console.log('mock implementation'));

Foo.doSomething();
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, thanks, that worked right away and was so simple!
0

After switching to jest 26.6, I found that none of these worked outside of tests (had been doing it directly below my imports, outside of any describe or it call). If I wanted any kind of mock implementation, I had to set it in the test, or in a beforeEach. If anyone can supply a link to the documentation on this, I'd be obliged.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.