Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock const method in jest?

I unit test code in typescript, use jest. Please teach me how to mock getData to return the expected value. My code as below:

// File util.ts
export const getData = async () => {
    // Todo something
    return data;
}

// File execution.ts import { getData } from './util';
function execute()
{
    // todo something
    const data = await getData();
    // todo something 
}
like image 894
Quoi Vo Avatar asked Feb 15 '19 05:02

Quoi Vo


People also ask

How do you mock a constant variable in Jest?

mock('../utils/deviceTypeUtils', () => ({ IsTablet: False, })); Describe('mock Const Example', () => { It('mock Const `isTablet` To The Value `true`', () => { DeviceTypeUtilsMock. isTablet = True; }); It('mock Const `isTablet` To The Value `false`', () => { DeviceTypeUtilsMock. isTablet = False; }); });

How do you mock a value in Jest?

It should be: let shallowWrapper; let withGoogleAnalytics; beforeEach(async () => { shallowWrapper = shallow(<Component />) jest. mock('config', () => ({ GOOGLE_ANALYTICS_TRACKING_ID: '123' })); withGoogleAnalytics = (await import('../withGoogleAnalytics')). default; });

How do you call a method in Jest?

call as mock function', () => { const outer = function() {}; outer. call = jest. fn(); const name = 'Aakash'; const age = 22; const tee = 'M'; callnapply. caller(this, outer, name, age, tee); expect(outer.

What does Jest fn () do?

The jest. fn method allows us to create a new mock function directly. If you are mocking an object method, you can use jest.

How to mock an imported function with jest?

To mock an imported function with Jest we use the jest.mock () function. jest.mock () is called with one required argument - the import path of the module we're mocking.

How do I mock a constructor function in jest?

In order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF). Since calls to jest.mock () are hoisted to the top of the file, Jest prevents access to out-of-scope variables.

What is mockimplementation () method in jest?

The mockImplementation () method is called with the new implementation as its argument. The new implementation will then be used in place of the previous one when the mock is called. We can combine this with jest.mock () factory functions to create mocked modules that contain mocked functions.

How do you test a function with a mock?

To test this function, we can use a mock function, and inspect the mock's state to ensure the callback is invoked as expected. All mock functions have this special .mock property, which is where data about how the function has been called and what the function returned is kept.


2 Answers

The problem is that your function returns a promise. Depends on how you use it there are several ways to mock it.

The simplest way would be to mock it directly, but then it will always return the same value:

// note, the path is relative to your test file
jest.mock('./util', () => ({ getData: () => 'someValue' }));

If you want to test both the resolved and the rejected case you need to mock getData so it will return a spy where you later on can change the implementation use mockImplementation. You also need to use async/await to make the test work, have a look at the docs about asynchronous testing:

import { getData } from './util';
jest.mock('./util', () => ({ getData: ()=> jest.fn() }));

it('success case', async () => {
  const result = Promise.resolve('someValue');
  getData.mockImplementation(() => result);

  // call your function to test
  await result; // you need to use await to make jest aware of the promise
});

it('error case', async () => {
  const result = Promise.reject(new Error('someError'));
  getData.mockImplementation(() => result);

  // call your function to test
  await expect(result).rejects.toThrow('someError');
});
like image 193
Andreas Köberle Avatar answered Oct 16 '22 17:10

Andreas Köberle


Try the following in your test file. Import the function from the module.

 import { getData } from './util';

Then mock the module with the function and its return value after all the import statements

jest.mock('./util', () => ({ getData: jest.fn() }))
getData.mockReturnValue("abc");

Then use it in your tests.

like image 22
anuragb26 Avatar answered Oct 16 '22 18:10

anuragb26