128

I am quite confused with mocking in Jest an how to unit test the implementations. The thing is i want to mock different expected behaviours.

Is there any way to achieve this? as imports can be only on the top of the file and to be able to mock something it must be declared before the import. I have also tried to pass a local function so I could overwrite the behaviour but jest complains you are not allowed to pass anything local.

jest.mock('the-package-to-mock', () => ({
  methodToMock: jest.fn(() => console.log('Hello'))
}));

import * as theThingToTest from '../../../app/actions/toTest'
import * as types from '../../../app/actions/types'

it('test1', () => {
  expect(theThingToTest.someAction().type).toBe(types.SOME_TYPE)
})

it('test2', () => {
  //the-package-to-mock.methodToMock should behave like something else
  expect(theThingToTest.someAction().type).toBe(types.SOME_TYPE)
})

internally as you can imagine theThingToTest.someAction() uses the-package-to-mock.methodToMock

Flip
  • 6,233
  • 7
  • 46
  • 75
Kanekotic
  • 2,824
  • 3
  • 21
  • 35
  • Does this answer your question? [How to change mock implementation on a per single test basis \[Jestjs\]](https://stackoverflow.com/questions/48790927/how-to-change-mock-implementation-on-a-per-single-test-basis-jestjs) – Rafael Tavares Nov 04 '21 at 14:19
  • This is the best answer that I found https://stackoverflow.com/a/68398254/9331978 – WestMountain Nov 18 '22 at 08:29

6 Answers6

228

You can mock with a spy and import the mocked module. In your test you set how the mock should behave using mockImplementation:

jest.mock('the-package-to-mock', () => ({
  methodToMock: jest.fn()
}));
import { methodToMock } from 'the-package-to-mock'

it('test1', () => {
  methodToMock.mockImplementation(() => 'someValue')
})

it('test2', () => {
  methodToMock.mockImplementation(() => 'anotherValue')
})
Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
  • 1
    thanks a lot for the answer, it works like a charm :) – Kanekotic Jul 12 '17 at 06:28
  • 28
    What if `methodToMock` is a constant property instead? – alayor Nov 23 '17 at 21:51
  • 2
    Why would you need to mock a constant value. Anyway, just replace `jest.fn()` with the value. Also no need to `import` the module then. – Andreas Köberle Nov 23 '17 at 21:57
  • 55
    I get mockImplementation() is not a function when I attempt this method. – phillyslick Jul 30 '18 at 19:58
  • 2
    `mockImplementation` will be undefined only if you forget to assign it to `jest.fn()`. I just tested – Andre Pena Jul 23 '20 at 16:19
  • If you get the mockImplementation is undefined error make sure that your function in jest.mock is wrapped in jest.fn(). For example: methodToMock: jest.fn((x) => x + 1) – Marnix.hoh Oct 21 '20 at 10:16
  • when importing es module, don't forget to add `__esModule: true` to the mocked object – sKopheK Dec 28 '20 at 12:19
  • What if the method to mock is the actual constructor? Can I require the actual module only in some tests? – Rayee Roded Mar 19 '21 at 17:20
  • What if it's not a method, but a constant? – cbdeveloper Aug 25 '22 at 09:45
  • 1
    Wow. I've learnt something new today. I didnt know you have to setup the mocking before importing the module. After 3 hours fidgeting. Thx – Gilbert Sep 17 '22 at 22:37
  • You should not have to mock before an import any more as jest hoists the `jest.mocks` now to my understanding. This causes an issue though if you try to create a const outside of the mock to a mocked function to check if that's been called and to provide proper typing. You will need to defer the call to the mocked function. Something like: `const mockedFn = jest.fn().mockResolvedValue('url'); jest.mock('@aws-sdk/s3-request-presigner', () => { return { getSignedUrl: jest.fn().mockImplementation(() => mockedFn()) } })` – CTS_AE Oct 04 '22 at 20:47
17

I use the following pattern:

'use strict'

const packageToMock = require('../path')

jest.mock('../path')
jest.mock('../../../../../../lib/dmp.db')

beforeEach(() => {
  packageToMock.methodToMock.mockReset()
})

describe('test suite', () => {
  test('test1', () => {
    packageToMock.methodToMock.mockResolvedValue('some value')
    expect(theThingToTest.someAction().type).toBe(types.SOME_TYPE)

  })
  test('test2', () => {
    packageToMock.methodToMock.mockResolvedValue('another value')
    expect(theThingToTest.someAction().type).toBe(types.OTHER_TYPE)
  })
})

Explanation:

You mock the class you are trying to use on test suite level, make sure the mock is reset before each test and for every test you use mockResolveValue to describe what will be return when mock is returned

Tal Joffe
  • 5,347
  • 4
  • 25
  • 31
12

Another way is to use jest.doMock(moduleName, factory, options).

E.g.

the-package-to-mock.ts:

export function methodToMock() {
  return 'real type';
}

toTest.ts:

import { methodToMock } from './the-package-to-mock';

export function someAction() {
  return {
    type: methodToMock(),
  };
}

toTest.spec.ts:

describe('45006254', () => {
  beforeEach(() => {
    jest.resetModules();
  });
  it('test1', () => {
    jest.doMock('./the-package-to-mock', () => ({
      methodToMock: jest.fn(() => 'type A'),
    }));
    const theThingToTest = require('./toTest');
    expect(theThingToTest.someAction().type).toBe('type A');
  });

  it('test2', () => {
    jest.doMock('./the-package-to-mock', () => ({
      methodToMock: jest.fn(() => 'type B'),
    }));
    const theThingToTest = require('./toTest');
    expect(theThingToTest.someAction().type).toBe('type B');
  });
});

unit test result:

 PASS  examples/45006254/toTest.spec.ts
  45006254
    ✓ test1 (2016 ms)
    ✓ test2 (1 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 toTest.ts |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        3.443 s

source code: https://github.com/mrdulin/jest-v26-codelab/tree/main/examples/45006254

Lin Du
  • 88,126
  • 95
  • 281
  • 483
7

spyOn worked best for us. See previous answer:

https://stackoverflow.com/a/54361996/1708297

Thomas Hagström
  • 4,371
  • 1
  • 21
  • 27
1

Andreas answer work well with functions, here is what I figured out using it:

// You don't need to put import line after the mock.
import {supportWebGL2} from '../utils/supportWebGL';


// functions inside will be auto-mocked
jest.mock('../utils/supportWebGL');
const mocked_supportWebGL2 = supportWebGL2 as jest.MockedFunction<typeof supportWebGL2>;

// Make sure it return to default between tests.
beforeEach(() => {
  // set the default
  supportWebGL2.mockImplementation(() => true); 
});

it('display help message if no webGL2 support', () => {
  // only for one test
  supportWebGL2.mockImplementation(() => false);

  // ...
});

It won't work if your mocked module is not a function. I haven't been able to change the mock of an exported boolean for only one test :/. My advice, refactor to a function, or make another test file.

export const supportWebGL2 = /* () => */ !!window.WebGL2RenderingContext;
// This would give you: TypeError: mockImplementation is not a function
Ambroise Rabier
  • 3,636
  • 3
  • 27
  • 38
1

How to Change Mocked Functions For Different Test Scenarios

In my scenario I tried to define the mock function outside of the jest.mock which will return an error about trying to access the variable before it's defined. This is because modern Jest will hoist jest.mock so that it can occur before imports. Unfortunately this leaves you with const and let not functioning as one would expect since the code hoists above your variable definition. Some folks say to use var instead as it would become hoisted, but most linters will yell at you, so as to avoid that hack this is what I came up with:

Jest Deferred Mocked Import Instance Calls Example

This allows us to handle cases like new S3Client() so that all new instances are mocked, but also while mocking out the implementation. You could likely use something like jest-mock-extended here to fully mock out the implementation if you wanted, rather than explicitly define the mock.

The Problem

This example will return the following error:

eferenceError: Cannot access 'getSignedUrlMock' before initialization

Test File

const sendMock = jest.fn()
const getSignedUrlMock = jest.fn().mockResolvedValue('signedUrl')

jest.mock('@aws-sdk/client-s3', () => {
  return {
    S3Client: jest.fn().mockImplementation(() => ({
      send: sendMock.mockResolvedValue('file'),
    })),
    GetObjectCommand: jest.fn().mockImplementation(() => ({})),
  }
})

jest.mock('@aws-sdk/s3-request-presigner', () => {
  return {
    getSignedUrl: getSignedUrlMock,
  }
})

The Answer

You must defer the call in a callback like so:

getSignedUrl: jest.fn().mockImplementation(() => getSignedUrlMock())

Full Example

I don't want to leave anything up to the imagination, although I phaked the some-s3-consumer from the actual project, but it's not too far off.

Test File

import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3'
import { SomeS3Consumer } from './some-s3-consumer'

const sendMock = jest.fn()
const getSignedUrlMock = jest.fn().mockResolvedValue('signedUrl')

jest.mock('@aws-sdk/client-s3', () => {
  return {
    S3Client: jest.fn().mockImplementation(() => ({
      send: sendMock.mockResolvedValue('file'),
    })),
    GetObjectCommand: jest.fn().mockImplementation(() => ({})),
  }
})

jest.mock('@aws-sdk/s3-request-presigner', () => {
  return {
    // This is weird due to hoisting shenanigans
    getSignedUrl: jest.fn().mockImplementation(() => getSignedUrlMock()),
  }
})

describe('S3Service', () => {
  const service = new SomeS3Consumer()

  describe('S3 Client Configuration', () => {
    it('creates a new S3Client with expected region and credentials', () => {
      expect(S3Client).toHaveBeenCalledWith({
        region: 'AWS_REGION',
        credentials: {
          accessKeyId: 'AWS_ACCESS_KEY_ID',
          secretAccessKey: 'AWS_SECRET_ACCESS_KEY',
        },
      })
    })
  })

  describe('#fileExists', () => {
    describe('file exists', () => {
      it('returns true', () => {
        expect(service.fileExists('bucket', 'key')).resolves.toBe(true)
      })

      it('calls S3Client.send with GetObjectCommand', async () => {
        await service.fileExists('bucket', 'key')

        expect(GetObjectCommand).toHaveBeenCalledWith({
          Bucket: 'bucket',
          Key: 'key',
        })
      })
    })

    describe('file does not exist', () => {
      beforeEach(() => {
        sendMock.mockRejectedValue(new Error('file does not exist'))
      })

      afterAll(() => {
        sendMock.mockResolvedValue('file')
      })

      it('returns false', async () => {
        const response = await service.fileExists('bucket', 'key')

        expect(response).toBe(false)
      })
    })
  })

  describe('#getSignedUrl', () => {
    it('calls GetObjectCommand with correct bucket and key', async () => {
      await service.getSignedUrl('bucket', 'key')

      expect(GetObjectCommand).toHaveBeenCalledWith({
        Bucket: 'bucket',
        Key: 'key',
      })
    })

    describe('file exists', () => {
      it('returns the signed url', async () => {
        const response = await service.getSignedUrl('bucket', 'key')

        expect(response).toEqual(ok('signedUrl'))
      })
    })

    describe('file does not exist', () => {
      beforeEach(() => {
        getSignedUrlMock.mockRejectedValue('file does not exist')
      })

      afterAll(() => {
        sendMock.mockResolvedValue('file')
      })

      it('returns an S3ErrorGettingSignedUrl with expected error message', async () => {
        const response = await service.getSignedUrl('bucket', 'key')

        expect(response.val).toStrictEqual(new S3ErrorGettingSignedUrl('file does not exist'))
      })
    })
  })

})
CTS_AE
  • 12,987
  • 8
  • 62
  • 63