Rohit Mittal
Rohit Mittal

Reputation: 427

Unable to Mock in Jest

I am trying to mock an API call using jest.mock method but mockResolvedValue give a compilation error Do I need to make some other changes?

enter image description here

Upvotes: 0

Views: 109

Answers (1)

Lin Du
Lin Du

Reputation: 102257

You can use ts-jest test helper - mocked.

The mocked test helper provides typings on your mocked modules and even their deep methods, based on the typing of its source.

E.g.

import axios from 'axios';
import { mocked } from 'ts-jest/utils';

jest.mock('axios');

describe('61863621', () => {
  it('should pass', async () => {
    const users = [{ name: 'Bob' }];
    const resp = { data: users };
    mocked(axios.get).mockResolvedValue(resp);
    await expect(axios.get('http://localhost')).resolves.toEqual(resp);
  });
});

The outcome of the test:

 PASS  stackoverflow/61863621/index.test.ts (9.461s)
  61863621
    ✓ should pass (4ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.791s

Upvotes: 1

Related Questions