【问题标题】:React Js API call Unit Test CaseReact Js API 调用单元测试用例
【发布时间】:2021-11-09 23:27:57
【问题描述】:

我正在尝试为我调用的 API 编写测试用例,但我不知道我做错了什么,我收到了这样的错误。

car.test.js

import { getCar } from "../Service/MainScreen/Cars/Car";

describe("Car  API Call function", () => {
  test("it should pass the test", () => {
    const testData = {
      id: 186,
      plate_number: "WW12345",
      status_display: "Aktywny",
      driver_name: "Jakub Nowak",
      driver_id: 181,
      created_at: "2021-08-12T09:07:30Z",
      vin: "WBADM123123123123",
      brand: "Ford",
      model: "Focus",
      "Brand-Model": "Ford/Focus",
      production: "2016",
      registration: "01-12-2020",
      insurance_date: "06-06-2023",
      has_registration_docs: true,
      has_policy_status: true,
      has_certificate: true,
      has_green_card: true,
      has_vehicle_card: true,
      has_car_picture: true,
      fleet_entry: "20-04-2018",
      monitoring_start: "12-08-2021",
      status: "Aktywny",
      Estimaed_distance: 29500,
      Estimaed_fuel: 1475,
      average_fuel: 5,
      claim: 1,
      cost: 1000,
    };

    const response = { json: jest.fn().mockResolvedValueOnce(testData) };
    global.fetch = jest.fn().mockResolvedValueOnce(response);

    return getCar().then((data) => {
      expect(data[0]).toEqual(testData);
    });
  });
});

GetCar 从“../../../Config/Api”导入配置;

export async function getCar() {
  return fetch(config.fakeapi.car, config.fakeHead)
    .then((response) => {
      return response.json();
    })
    .catch((reject) => console.log(reject));
}

这是我附上的图片中的错误,有人可以帮我解决我的测试用例,我也可以为另一个 API 调用编写

【问题讨论】:

    标签: javascript reactjs unit-testing react-testing-library react-testing


    【解决方案1】:

    testData 不是数组,这就是为什么data[0] 给你undefined。应该是:

    const response = { json: jest.fn().mockResolvedValueOnce(testData) };
    global.fetch = jest.fn().mockResolvedValueOnce(response);
    
    return getCar().then((data) => {
      expect(data).toEqual(testData);
    });
    

    【讨论】:

      猜你喜欢
      • 2021-10-16
      • 2019-08-29
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多