【问题标题】:How to retrieve data from msw mock request body如何从 msw 模拟请求正文中检索数据
【发布时间】:2022-10-06 17:56:01
【问题描述】:

我正在尝试在使用 Typescript 时使用 msw 从模拟 api 调用中检索数据。我该怎么做呢?我不断收到 \"Property \'email\' 在类型 \'DefaultBodyType\'\ 上不存在"

处理程序

export const handlers: RestHandler[] = [
  rest.post(`/${API_VERSION}/authentication/login`, (req, res, ctx) => {
    const {email} = req.body;
    console.log();
    return res(
      ctx.status(200),
      ctx.json({
        token: \"abdb23231232jdsaWEDwdxaCDA\",
        expiresIn: 100000,
        isEnabled: true,
        isLocked: false,
      })
    );
  })
];

    标签: reactjs msw


    【解决方案1】:

    您需要为处理程序本身提供一些类型,描述请求正文和响应正文应该是什么样子。

    interface LoginRequestBody {
      email: string;
    }
    
    interface LoginResponseBody {
      token: string,
      expiresIn: number;
      isEnabled: boolean;
      isLocked: boolean,
    }
    
    export const handlers = [
      rest.post<LoginRequestBody, LoginResponseBody>(`/${API_VERSION}/authentication/login`, (req, res, ctx) => {
        const {email} = req.body;
        console.log();
        return res(
          ctx.status(200),
          ctx.json({
            token: "abdb23231232jdsaWEDwdxaCDA",
            expiresIn: 100000,
            isEnabled: true,
            isLocked: false,
          })
        );
      })
    ];
    

    你也不需要RestHandler[],因为它是推断的。

    由 MSW 维护者编写的This article 也可能有助于更多地了解类型。

    【讨论】:

      猜你喜欢
      • 2021-07-21
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      • 2022-12-30
      相关资源
      最近更新 更多