You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Jest测试API是否返回200状态码(含Rick&Morty API示例)

解决Jest测试API状态码的问题

先给你梳理下代码里的核心问题:

  • jest.mock('getMovies') 用法完全错了,你要mock的是axios而不是自己写的模块
  • getMovies是异步函数,但你没处理异步逻辑,而且原函数里没返回请求响应,导致getMovies.status根本不存在
  • 测试用例既没正确调用异步函数,也没等待结果就断言

下面给你两种可行的实现方案:


方案1:发送真实API请求(适合简单场景)

先修改你的mock.js,让函数返回请求响应:

import axios from "axios";

// 函数名改成getCharacters更贴合API内容
const getCharacters = async () => {
    try {
        const res = await axios.get('https://rickandmortyapi.com/api/character');
        return res; // 返回响应对象,测试时才能拿到status
    } catch(error) {
        console.error('请求出错:', error);
        throw error; // 抛出错误,让测试能捕获到失败情况
    }
}

export default getCharacters;

然后编写测试文件mock.test.js,注意用async/await处理异步:

import getCharacters from './mock.js';

test('API返回200状态码', async () => {
    const response = await getCharacters();
    expect(response.status).toBe(200);
});

方案2:Mock Axios(避免发送真实请求,适合复杂测试场景)

如果不想每次测试都发真实请求,可以mock axios的get方法:

测试文件mock.test.js修改如下:

import axios from 'axios';
import getCharacters from './mock.js';

// Mock整个axios模块
jest.mock('axios');

test('API返回200状态码', async () => {
    // 模拟axios.get返回的成功响应
    axios.get.mockResolvedValue({ status: 200 });
    
    const response = await getCharacters();
    expect(response.status).toBe(200);
    // 额外验证axios.get是否被正确调用
    expect(axios.get).toHaveBeenCalledWith('https://rickandmortyapi.com/api/character');
});

原mock.js的修改和方案1一致,需要返回响应对象。


关于你之前的报错解释

你看到的Cannot read properties of undefined (reading 'status')报错,是因为getMovies是一个函数,你直接访问它的status属性(函数本身没有这个属性);再加上你错误地用jest.mock('getMovies')把自己的函数变成了空mock函数,自然找不到status属性。

内容的提问来源于stack exchange,提问作者Alan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 13:41:40