【问题标题】:How to write JEST test cases for the callback API如何为回调 API 编写 JEST 测试用例
【发布时间】:2019-05-26 03:49:08
【问题描述】:

我创建了一个 API 服务工厂,动态传递 URL,函数作为参数。一旦成功,数据就会进入回调函数,并且可以按预期正常工作。同样,我将编写 JEST 测试用例。 我无法找到正确的方法。可以帮助某人。非常感谢。

代码在这里

function userLogin(username, password) {
  const reqBody = {
    companyEmailAddress: username,
    password,
  };
  const url = `${config.apiBaseUrl}${serviceMethodConstants.login}`;
  return (dispatch) => {
    dispatch(serviceFactory.postData(url, false, reqBody, function (response, dispatch) {
      if (response !== undefined) {
        console.log(response )
      }
    }));
  };
}

同样,我编写了 JEST 测试用例,但它没有按预期显示任何错误或成功消息。

JEST 测试代码

import { userConstants } from './constants';
import { serviceFactory } from '../../services/_helpers/serviceFactory';

const loginData = {
  companyEmailAddress: 'rameshffdfdf.lambanihghgh@gmail.com',
  password: 'Ramesh@1',
};

axiosMock.onPost(routeUrl).reply(200, JSON.stringify(loginData));
const spy = jest.spyOn(axios, 'post');
await store.dispatch(userActions.userLogin(...loginData, function (response, dispatch) {
    expect(response.message).toEqual('Failure');
    expect(spy).toBeCalled();
}));

【问题讨论】:

    标签: reactjs jestjs babel-jest jest-fetch-mock


    【解决方案1】:

    userLogin 动作创建者(thunk)不接受回调并且不执行请求。未知 store.dispatch 是否返回一个可以等待的承诺。

    单元测试的正确策略是模拟除测试单元之外的所有内容。由于 serviceFactory 抽象正在使用中,因此不应涉及 Axios。也可以在不涉及 Redux 的情况下测试 Action creator。

    const dispatch = jest.fn();
    const postDataResult = {};
    jest.spyOn(serviceFactory, 'postData').mockReturnValue(postDataResult);
    
    userActions.userLogin('user', 'pass')(dispatch);
    
    expect(serviceFactory.postData).toBeCalledWith(url, false, {...}, expect.any(Function));
    expect(dispatch).toBeCalledWith(postDataResult);
    

    测试可以通过这种方式保持同步。

    【讨论】:

    • 谢谢你的回复,我按照你说的做了。我收到一个错误参数传递。您能否检查并帮助我,以获取更多参考内附的屏幕截图。
    • logn 是错误的函数,因为调用的回调 postData 是匿名的。您应该将参数声明为expect.any(Function),而不是logn。另一个问题是...loginData。我没有考虑你的情况,但当然,传播是行不通的——它不是一个数组。
    • 现在,没有错误工作正常。有没有办法使用响应或失败对象检查成功和失败 API 类?
    • 什么意思? “API 类”指的是什么?
    • API(应用程序接口)Web服务调用,希望在JEST测试用例中显示,Web服务调用是否正确完成与成功和失败场景。
    猜你喜欢
    • 1970-01-01
    • 2021-06-20
    • 2021-08-29
    • 2019-04-24
    • 2021-08-10
    • 2020-02-17
    • 2021-10-16
    • 2018-09-17
    • 1970-01-01
    相关资源
    最近更新 更多