【问题标题】:How can i "intercept" request in jest using enzyme?我如何使用酶开玩笑地“拦截”请求?
【发布时间】:2019-02-28 10:07:19
【问题描述】:

我有一个使用来自redux-api-middleware 的 RSAA 的操作,称为 createUser:

export const createUser = values => {
  const email = values.get("user_attributes[email]");
  const password = values.get("user_attributes[password]");
  return dispatch => {
    dispatch({
      [RSAA]: {
        endpoint: `${globalVar.API_URL}/users/`,
        method: "POST",
        body: values,
        types: [
          CREATE_USER,
          {
            type: CREATE_USER_SUCCESS,
            payload: (action, state, response) => {
              return response.json().then(json => {
                dispatch(login(email, password));
                dispatch(sendFlashMessage("success", json.message));
                return json;
              });
            }
          },
          CREATE_USER_FAILURE
        ]
      }
    });
  };
};

...我有一个带有redux-form 的组件使用此操作:

class UserNew extends Component {
  constructor(props) {
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onSubmit(values) {
    values = { user_attributes: values };
    const data = objectToFormData(values);
    this.props.actions.createUser(data);
  }

  render() {
    const { handleSubmit, errors } = this.props;
    return (
      <UserForm
        handleSubmit={handleSubmit}
        onSubmit={this.onSubmit}
        errors={errors}
      />
    );
  }
}

在我的jestenzyme 测试文件中:

it("create new user", done => {
  wrapper
    .find("#sign-up")
    .hostNodes()
    .simulate("click");

  wrapper
    .find('[name="first_name"]')
    .hostNodes()
    .simulate("change", { target: { value: "User" } });

 ... 

...填写表格后:

wrapper
  .find("form")
  .hostNodes()
  .simulate("submit");
done();

但它崩溃了:

所以,我想拦截 API 调用并让它完成执行操作(发送登录和 sendFlashMessage)。

我试过moxios,但没用:

moxios.install();
moxios.stubRequest(`${globalVar.API_URL}/users/`, {
  status: 200,
  response: [{user: {...}, message: "OK"}]
});

我正在尝试使用sinon 来解决这个问题

【问题讨论】:

  • 发布你的sinon代码
  • 什么是RSAA?谷歌什么也没告诉我
  • 我认为RSAA和CALL_API是一样的:import { CALL_API, RSAA } from 'redux-api-middleware';
  • 嘿,你的问题得到回答了吗?

标签: reactjs jestjs sinon enzyme jsdom


【解决方案1】:

enzymejestsinon 一起使用。

示例代码:

import { mount } from "enzyme";
import sinon from "sinon";

beforeAll(() => {
 server = sinon.fakeServer.create();
 const initialState = {
  example: ExampleData,
  auth: AuthData
 };
 wrapper = mount(
  <Root initialState={initialState}>
    <ExampleContainer />
  </Root>
 );
});

it("example description", () => {
  server.respondWith("POST", "/api/v1/example", [
    200,
      { "Content-Type": "application/json" },
      'message: "Example message OK"'
    ]);
  server.respond();
  expect(wrapper.find(".response").text().to.equal('Example message OK');
})

在上面的代码中,我们可以看到如何使用酶创建的测试 DOM 拦截 API 调用,然后使用 sinon 模拟 API 响应。

【讨论】:

    【解决方案2】:

    Sinon 没有任何直接的方法可以使用它的假 XHR 机器为您解决这个问题。从您使用的middleware documentation 可以清楚地看出原因:

    注意:redux-api-middleware 依赖于可用的全局 Fetch,并且可能需要针对您的运行时环境的 polyfill。

    Sinon(或者实际上是它的依赖 nise library)不处理 Fetch,只处理 XHR。

    您可以使用像fake-fetch 这样的库,也可以自己简单地存根fetch。不过,这将涉及相当复杂的存根,包括存根复杂的响应,所以我宁愿这样做:

    var fakeFetch = require('fake-fetch');
    
    beforeEach(fakeFetch.install);
    afterEach(fakeFetch.restore);
    
    it("should fetch what you need", done => {
      fakeFetch.respondWith({"foo": "bar"});
    
      fetch('/my-service', {headers: new Headers({accept: 'application/json'})}).then(data => {
        expect(fakeFetch.getUrl()).toEqual('/my-service');
        expect(fakeFetch.getMethod()).toEqual('get');
        expect(data._bodyText).toEqual('{"foo":"bar"}');
        expect(fakeFetch.getRequestHeaders()).toEqual(new Headers({accept: 'application/json'}));
        done();
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-21
      • 2020-07-20
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      相关资源
      最近更新 更多