axios 接收的函数未在JEST中抛出

hmmo2u0o  于 2023-03-02  发布在  iOS
关注(0)|答案(1)|浏览(97)

我尝试测试当API抛出错误时,我的函数是否正确地抛出错误。
这是我的主要职责

export const fetchRate = async (symbol = "BTC") => {
  try {
    const response = await axios.get(
      `https://rest.coinapi.io/v1/exchangerate/${symbol}/USD`,
      headers
    );
    return response;
  } catch (e) {
    throw e.response.data.error;
  }
};

这就是考验

test("If incorrect symbol is passed the function throws an error", async () => {
  const e = {
    response: {
      data: {
        error: "We didn't find your currency",
      },
      status: 550,
    },
  };
  axios.get.mockRejectedValueOnce(e)
  await expect(fetchRate()).rejects.toThrow("We didn't find your currency");
});

我希望,既然我抛出了catch块,这个测试应该可以工作,但是我不断地得到接收函数没有抛出。

uoifb46i

uoifb46i1#

参见issue#12024
rejects.toThrow链要求抛出实际的Error对象
您抛出了一个string,而不是catch块中的Error,因此需要使用.rejects.toEqual()
例如
index.ts

import axios from "axios";

export const fetchRate = async (symbol = 'BTC') => {
  try {
    const response = await axios.get(`https://rest.coinapi.io/v1/exchangerate/${symbol}/USD`);
    return response;
  } catch (e) {
    throw e.response.data.error;
  }
};

index.test.ts

import axios from 'axios';
import { fetchRate } from '.';

describe('75534184', () => {
  test('If incorrect symbol is passed the function throws an error', async () => {
    const e = {
      response: {
        data: {
          error: "We didn't find your currency",
        },
        status: 550,
      },
    };
    jest.spyOn(axios, 'get').mockRejectedValueOnce(e);
    await expect(fetchRate()).rejects.toEqual("We didn't find your currency");
  });
});

试验结果:

PASS  stackoverflow/75534184/index.test.ts (8.379 s)
  75534184
    ✓ If incorrect symbol is passed the function throws an error (3 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |    87.5 |      100 |     100 |   83.33 |                   
 index.ts |    87.5 |      100 |     100 |   83.33 | 6                 
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.185 s, estimated 11 s
Ran all test suites related to changed files.

相关问题