why actual and expected length is not equal in react js

老子叫甜甜 提交于 2019-12-11 14:56:14

问题


could you please tell me why actual and expected length is not equal in react js here is my code

https://codesandbox.io/s/oq7kwzrnj5

mockAxios.get.mockImplementation(() =>
      Promise.resolve({
        data: {
          data: ['a','b']
        }
      }));

I am sending 2 elements on array but getting 0 element

it("axios call check or not", async () => {
      const wrapper = shallow(<List />);
      expect(mockAxios.get).toHaveBeenCalledTimes(1);

      expect(wrapper.find("li").length).toBe(2);

    });


回答1:


You are making async call in ComponentDidMount. Async means 'do not wait', so using wrapper.debug(), you can see that it contains no li tag since initial state of items is [], once call is done, it updates the state and re-renders the DOM.

And wrapper in the enzyme is immutable. So you can update the state in your test case, and then check for the li tag length in the wrapper. Also, I would advise making an async call in ComponentWillMount, for your use case. The way you mocked API and the response doesn't make sense to me, have used "axios-mock-adapter" which was already present in package.json. :)

Here is the working example: https://codesandbox.io/s/30jp9vk67q

import React from "react";
import { shallow, mount } from "enzyme";
import List from "./ListItem";
import Enzyme from "enzyme";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";

describe("List Components", () => {
  var mock = new MockAdapter(axios);
  beforeEach(() => {
    mock
     .onGet("https://biz.timesofindia.indiatimes.com/bankifsc/getlist")
      .reply(200, {
        data: [{ text_val: "a" }, { text_val: "b" }]
      });
  });

  describe("List Items", () => {
    it("check length", () => {
      const wrapper = shallow(<List />);
      console.log("Wrapper-Before-", wrapper.debug());
      wrapper.setState({ items: [{ text_val: "a" }, { text_val: "b"}]})
      console.log("Wrapper-After-", wrapper.debug());
      expect(wrapper.find("li").length).toBe(2);
    });
  });
});


来源:https://stackoverflow.com/questions/49829698/why-actual-and-expected-length-is-not-equal-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!