ReactJS组件状态返回空数据,即使在笑话/酶测试中设置成功



我有一个简单的方法从API获取数据并更新Grid组件中的状态

//in the constructor
this.state = {
blogs: []
};
//method here
updateBlogsTable() {
Axios.get("/api/blogs").then(response => {
this.setState({ blogs: response.data.data });
});
//omitting catch block for brevity
}

此方法从componentDidMount和刷新按钮的click处理程序调用

componentDidMount() {
this.updateBlogsTable();
}

<Button
id="refreshBlog"
icon="pi pi-refresh"
style={{ float: "right" }}
onClick={this.updateBlogsTable}
/>

刷新按钮测试未通过

describe("Blog Grid", () => {
let response = {
data: {
data: [
{
title: "title one",
published: false,
publish_date: null,
slug: "title-one"
},
{
title: "title two",
published: false,
publish_date: null,
slug: "title-two"
}
],
links: {
self: "link-value",
first: "http://adminpanel.test/api/blogs?page=1",
last: null,
prev: null,
next: null
},
meta: {
current_page: 1,
from: 1,
path: "http://adminpanel.test/api/blogs",
per_page: 20,
to: 2
}
}
};
it("refreshes blogs", () => {
axios.get.mockImplementationOnce(() => Promise.resolve(response));
const grid = mount(<Grid />);
let refreshResponse = Object.assign({}, response);
refreshResponse.data.data.push({
title: "title three",
published: true,
publish_date: null,
slug: "title-three"
});
axios.get.mockImplementationOnce(() =>
Promise.resolve(refreshResponse)
);
grid.find("#refreshBlog")
.at(0)
.simulate("click");
expect(grid.state().blogs).toEqual(refreshResponse.data.data);
});

});

grid.state().blogs返回未通过测试的[]

FAIL resources/js/tests/Blogs/Grid.test.js (5.765s)
Blog Grid
✓ renders without errors (235ms)
✕ refreshes blogs (161ms)
● Blog Grid › refreshes blogs
expect(received).toEqual(expected) // deep equality

当我将console.log(this.state.blogs);添加到updateBlogsTable()方法时;我能看到

console.log resources/js/views/Blogs/Grid/Grid.js:25
[ { title: 'title one',
published: false,
publish_date: null,
slug: 'title-one' },
{ title: 'title two',
published: false,
publish_date: null,
slug: 'title-two' },
{ title: 'title three',
published: true,
publish_date: null,
slug: 'title-three' } ]

为什么grid.state().blogs在测试中仍然是一个空数组?

由于promise.gets是异步调用的,所以一旦模拟按钮单击,您的状态就不会更新。

我在测试组件时也遇到过类似的问题,我可以考虑解决这个问题的一种方法是——从updateBlogTable返回承诺,并在测试中订阅then,并在该then中进行断言。

类似这样的东西-

updateBlogsTable() {
let p = Axios.get("/api/blogs").then(response => {
this.setState({ blogs: response.data.data });
});
return p;
}
grid.instance().updateBlogsTable().then(() => {
expect(grid.state().blogs).toEqual(refreshResponse.data.data);
})

甚至我想知道它是否可以通过模拟按钮点击直接测试。

如果这有帮助,请告诉我。

最新更新