0

Is there a way to dynamically update a next/router/ jest.mock query?

I am essentially trying to mock a different query depending on the tests that are run.

i.e.

    jest.mock('next/router', () => ({
        useRouter() {
            return {
                query: {
                    'block-number': ['block', '1']
                }
            };
        }
    }));

describe('test block 1 ', () => {
    test('Renders block 1', async () => {
 
        });
    });

The above mock should be run for describe block 1

and then mock should be updated to run the block 2 with different a different query i.e.

jest.mock('next/router', () => ({
        useRouter() {
            return {
                query: {
                    'block-number': ['block', '2']
                }
            };
        }
    }));

describe('test block 2 ', () => {
    test('Renders block 2', async () => {
 
        });
    });

so essentially I want to be able to update the query in the jest.mock

user6248190
  • 1,233
  • 2
  • 16
  • 31
  • Why did you delete your question about copying files with boto3? If you solved it, its better to leave it and a provide the correct answer if mine was incorrect. – Marcin May 10 '22 at 04:48

1 Answers1

0

What you are looking for is either mockImplementationOnce or mockReturnValueOnce.

import { useRouter } from 'next/router';
jest.mock('next/router', () => {
  return {
    ...jest.requireActual('next/router'),
    useRouter: jest.fn(() => ({
      query: 'initial',
    })),
});

describe('wrapper', () => {
  beforeEach(() => {
    useRouter.mockClear();
  });

  describe('one', () => {
    test('does one', () => {
      useRouter.mockReturnValueOnce({ query: '' });
      // expectations...
    });
  });

  describe('two', () => {
    test('does two', () => {
      useRouter.mockReturnValueOnce({ query: 'something-diff' });
      // expectations...
    });
  });
});

You might need to tweak the mock, i'm not sure what the exact return value should be, but this should set you on the right path.

alextrastero
  • 3,703
  • 2
  • 21
  • 31
  • Thanks this look promising however I am getting the following error: ` ReferenceError: Cannot access 'mockUseRouter' before initialization` – user6248190 Oct 13 '21 at 12:43
  • I've updated the answer, the concept is that you basically tell jest that a method is a mock, and then you import that method (which is now a mock) and you change the implementation. – alextrastero Oct 13 '21 at 13:24
  • Thank you for the update but it does not seem to work, I get the following error: `Uncaught [TypeError: Cannot read property 'query' of undefined` – user6248190 Oct 13 '21 at 13:34
  • on the inital mock do `useRouter: jest.fn(() => ({ query: 'initial' }))` – alextrastero Oct 13 '21 at 13:38
  • `useRouter: jest.fn(),` means that calling useRouter will return undefined, so if you need it, you can add some default value and then change per test – alextrastero Oct 13 '21 at 13:38