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
}
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; }); });
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; });
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.
The jest. fn method allows us to create a new mock function directly. If you are mocking an object method, you can use 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.
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.
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.
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.
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');
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With