Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

271
Views
How to mock default exported modules with jest

The problem

I'm trying to mock the default exported part of a module, which looks like this:

// test.js
const testVariable = {
    blabla: {
        test: 'testContent'
    }
};

export const anotherNotNeedToMockVariable = {};
export default testVariable;

The variable I actually need to mock is test.

What I've tried

This implementation gives me an error: Cannot spy the default property because it is not a function

// toTestModule.js
import test from './test'

export const toTestModuleFunc = async () => {
  console.log('variable mocked', test.blabla.test);
  return test.blabla.test;
};



import * as test from '../test'
import {toTestModuleFunc} from '../toTestModule'

describe('test', () => {
  it('with jest.mock()', async () => {
    const newValue = 'newValue';

    jest.mock('../test', () => ({
        blabla: {
            test: newValue
        }
    }));


    const value = await toTestModuleFunc();
    // this fails
    expect(value).toEqual(newValue);
  });

  it('with jest.spyOn()', async () => {
    const newValue = 'newValue';

    jest.spyOn(test, 'default', 'get').mockImplementation(() => {
      return ({
          blabla: {
              test: newValue
          }
      });
    });


    const value = await toTestModuleFunc();
    // this fails
    expect(value).toEqual(newValue);
  });
});

If I change the jest.spyOn(test, 'default') to jest.spyOn(test, 'default', 'get') it gives me another error: Property default does not have access type get

I tried to use jest.mock() function, but it does not work with that it never returns the mocked value.

I'd really apreciate any help.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!