简体   繁体   English

Mock Service Worker-Expected 响应解析器返回模拟响应对象但未定义。 将改为使用原始响应

[英]Mock Service Worker-Expected response resolver to return a mocked response Object but got undefined. The original response is going to be used instead

React Testing Using Mock service worker is returning undefined and then taking values from the actual API. React Testing Using Mock service worker 返回未定义,然后从实际 API 中获取值。 As you can see from the image down below the test is getting passed by getting values from the actual API and the name ARLO WANG is getting pulled out.正如您从下方图片中看到的那样,通过从实际 API 获取值来通过测试,并且名称 ARLO WANG 被提取出来。 Where as the name I have kept in the mockResponse is "first last" in the handler.js file.我在 mockResponse 中保留的名称在 handler.js 文件中是“first last”。

FollowersList.js粉丝列表.js

import React, { useEffect, useState } from 'react'
import "./FollowersList.css"
import axios from "axios"
import { Link } from 'react-router-dom';
import { v4 } from 'uuid';

export default function FollowersList() {

    const [followers, setFollowers] = useState([]);

    useEffect(() => {
        fetchFollowers()
    }, []);

    const fetchFollowers = async () => {
        const {data} = await axios.get("https://randomuser.me/api/?results=5")
        setFollowers(data.results)
    }
    // console.log(followers)

    return (
        <div className="followerslist-container">
            <div>
                {followers.map((follower, index) => (
                    <div className="follower-item" key={v4()} data-testid={`follower-item-${index}`}>
                        <div className="followers-details">
                            <div className="follower-item-name">
                                <h4>{follower.name.first}</h4> <h4>{follower.name.last}</h4>
                            </div>
                            <p>{follower.login.username}</p>
                        </div>
                    </div>
                ))}
            </div>
            <div className="todo-footer">
                <Link to="/">Go Back</Link>
            </div>
        </div>
    )
}

FollowersList.test.js关注者列表.test.js

import { render, screen } from "@testing-library/react";
import { BrowserRouter } from "react-router-dom";
import FollowersList from "../FollowersList";


const MockFollowersList = () => {
  return (
    <BrowserRouter>
      <FollowersList />
    </BrowserRouter>
  );
};

describe("FollowersList Component", () => {
  test("renders first follower", async () => {
    render(<MockFollowersList />);
    screen.debug()
    expect(await screen.findByTestId("follower-item-0")).toBeInTheDocument();
  });
});

src/mock/handler.js src/mock/handler.js

import { rest } from 'msw';

const mockResponse = {
  data: {
    results: [
      {
        name: {
          first: "first",
          last: "last",
        },
        login: {
          username: "x",
        },
      },
    ],
  },
};

export const handlers = [
  rest.get('https://randomuser.me/api/', (req, res, ctx) => {
    return res(ctx.json({mockResponse}))
    }
  })
]

VSCODE terminal VSCODE终端

Something is going wrong in the return line in handlers array in the handler file.处理程序文件中处理程序数组的返回行出现问题。 It's not sending back the mockResponse correctly.它没有正确发回 mockResponse。

Found the mistake.发现错误。 The response structure returned by the actual API and the msw is different.实际API和msw返回的response structure是不一样的。 Just had to remove the 'data' object in the mockResponse and keep the it just as an array of 'results'.只需删除 mockResponse 中的“数据”对象并将其保留为“结果”数组即可。

import { rest } from 'msw';

const mockResponse = {
  results: [
    {
      name: {
        first: "first",
        last: "last",
      },
      login: {
        username: "x",
      },
    },
  ],
};

export const handlers = [
  rest.get('https://randomuser.me/api/', (req, res, ctx) => {
    return res(ctx.json(mockResponse))
    }
  })
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM