为什么React JS中的实际长度和预期长度不相等 [英] why actual and expected length is not equal in react js
问题描述
能否请您告诉我为什么React JS中的实际长度和预期长度不相等 这是我的代码
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']
}
}));
我在数组上发送了2
个元素,但是却获得了0
个元素
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);
});
推荐答案
您正在ComponentDidMount中进行 async 调用.异步意味着不要等待",因此使用wrapper.debug(),您可以看到它不包含 li 标记,因为项的初始状态为[],一旦调用完成,它将更新状态并重新渲染DOM.
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.
酶中的包装材料是不可变的.因此,您可以在测试用例中更新状态,然后在包装器中检查 li 标记的长度.另外,对于您的用例,我建议在ComponentWillMount中进行异步调用. 您嘲笑API和响应的方式对我来说没有意义,使用了package.json中已经存在的"axios-mock-adapter". :)
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. :)
这是工作示例: https://codesandbox.io/s/30jp9vk67q >
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);
});
});
});
这篇关于为什么React JS中的实际长度和预期长度不相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!