Jest mock an es6 named imported object

Viewed 159

I would like to know how can I mock an imported object for return a fake value with Jest.

In this case, I want to override the default timeout value (5000) to 1000 to crash my function

// config.ts
export const config = {
  request: {
    timeout: 5000,
  },
};
// Test file
import * as config from './config';

describe('Requests', () => {
  beforeEach(() => {
    jest.mock('./config');
  });

  afterEach(() => {
    jest.resetAllMocks();
  });

  it('Force timeout value', () => {
    jest.mock('./config');
    config.request.timeout.mockReturnValueOnce(1000);

    expect(config.request.timeout).toEqual(1000); // FAIL: returns 5000 instead of 1000
  });
});

Thank you!

1 Answers

UPDATED ANSWER

In this case, you have to use Require instead of import (ESM).

// config.ts
export const config = {
  request: {
    timeout: 5000
  }
}

The test file will look like this:

// Test file

describe('greetings', () => {
  beforeEach(() => jest.resetModules())

  describe('hello', () => {
    describe('when the language is set to galician', () => {
      it('returns galician for hi', () => {
        jest.mock('./config', () => ({ request: { timeout: 1000 } }))
        const { request } = require('./config')
        expect(request.timeout).toEqual(1000)
      })
    })

    describe('when the language is not set to galician', () => {
      it('returns hi', () => {
        jest.mock('./config', () => ({ request: { timeout: 2000 } }))
        const { request } = require('./config')
        expect(request.timeout).toEqual(2000)
      })
    })
  })
})

reference - https://medium.com/trabe/mocking-different-values-for-the-same-module-using-jest-a7b8d358d78b

Related