最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to properly use axios.get.mockResolvedValue for async calls in jest - Stack Overflow

programmeradmin3浏览0评论

I want to mock the returned value in the catch block of an async function with Jest

This is the function I am writing the unit test for:

  try {
    make some axios request
    }
    return users;
  } catch (err) {
    return new Map();
  }
};

    it('should catch error when query is unsuccessful', async () => {
      axios.get.mockRejectedValue(new Map());
      const res = getUserDataByIds('someUserIds');
      await expect(res).rejects.toThrow();
    });

I am getting the error from Jest:

 expect(received).rejects.toEqual()
 Received promise resolved instead of rejected
 Resolved to value: Map {}

I expect that the test should pass because I'm mocking a rejected value.

I want to mock the returned value in the catch block of an async function with Jest

This is the function I am writing the unit test for:

  try {
    make some axios request
    }
    return users;
  } catch (err) {
    return new Map();
  }
};

    it('should catch error when query is unsuccessful', async () => {
      axios.get.mockRejectedValue(new Map());
      const res = getUserDataByIds('someUserIds');
      await expect(res).rejects.toThrow();
    });

I am getting the error from Jest:

 expect(received).rejects.toEqual()
 Received promise resolved instead of rejected
 Resolved to value: Map {}

I expect that the test should pass because I'm mocking a rejected value.

Share Improve this question edited Oct 8, 2019 at 5:08 Lin Du 102k135 gold badges332 silver badges564 bronze badges asked Oct 7, 2019 at 16:24 baconLikeTheKevin725baconLikeTheKevin725 2451 gold badge4 silver badges11 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

You can create a mocked function to replace axios.get() method.

index.ts:

import axios from 'axios';

export async function getUserDataByIds(ids: string[]) {
  try {
    const users = await axios.get('/users');
    return users;
  } catch (err) {
    return new Map();
  }
}

index.spec.ts:

import { getUserDataByIds } from './';
import axios from 'axios';

describe('getUserDataByIds', () => {
  it('should return empty Map when axios.get failed', async () => {
    const getError = new Error('network error');
    axios.get = jest.fn().mockRejectedValue(getError);
    const actualValue = await getUserDataByIds(['1']);
    expect(actualValue).toEqual(new Map());
    expect(axios.get).toBeCalledWith('/users');
  });

  it('should return users', async () => {
    const mockedUsers = [{ userId: 1 }];
    axios.get = jest.fn().mockResolvedValue(mockedUsers);
    const actualValue = await getUserDataByIds(['1']);
    expect(actualValue).toEqual(mockedUsers);
    expect(axios.get).toBeCalledWith('/users');
  });
});

Unit test result with 100% coverage:

 PASS  src/stackoverflow/58273544/index.spec.ts
  getUserDataByIds
    ✓ should return empty Map when axios.get failed (12ms)
    ✓ should return users (4ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        5.597s, estimated 7s

Source code: https://github./mrdulin/jest-codelab/tree/master/src/stackoverflow/58273544

发布评论

评论列表(0)

  1. 暂无评论