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

183
Views
How to mock a function inside a nested ES6 imports using jest?

I have following two modules.

// exchange.ts

export async function fetchBalances(exchangeIds: string[]): Promise<ExchangeBalance> { /* ... */}
// normalizer.ts

import { fetchBalances } from './exchange';

export async function scaleFactor() {
  const balances = await fetchBalances([...]);
  // ....
}

I am trying to mock fetchBalances of exchange when testing normalizer as follows:

// normalizer.test.ts

beforeEach(() => {
  jest.resetModules();
});

async function mockExchange() {
  jest.doMock('../src/exchange', () => {
    return {
      __esModule: true,

      fetchBalances: async (exchangeIds: string[]): Promise<ExchangeBalance> => {
        return {/* ... */};
      }
    };
  });

  return (await import('../src/exchange'));
}

test('returns 1', async () => {
    // 1
    const moduleName = await mockExchange();
    console.log(await moduleName.fetchBalances([...]));

    // 2
    const scaleFactor = await scaleFactor();
    expect(scaleFactor).toEqual(1);
});
  1. Direct call to moduleName uses mock & doesnt call API. All good here.
  2. However, calls to scaleFactor does not use mock & runs real implementation of fetchBalances.

How can I make normalizer to use mocks of fetchBalances ?

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!