Javascript 即使在jest/Ezyme测试中成功设置,ReactJS组件状态仍返回空数据

Javascript 即使在jest/Ezyme测试中成功设置,ReactJS组件状态仍返回空数据,javascript,reactjs,jestjs,enzyme,Javascript,Reactjs,Jestjs,Enzyme,我有一个简单的方法从API获取数据并更新网格组件中的状态 //in the constructor this.state = { blogs: [] }; //method here updateBlogsTable() { Axios.get("/api/blogs").then(response => { this.setState({ blogs: response.data.data }); }); //omitting catch

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

//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
调用此方法,然后刷新按钮的
单击
处理程序

componentDidMount() {
    this.updateBlogsTable();
}

当我添加
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.state是异步调用的,只要您单击模拟按钮,您的状态就不会得到更新

我在测试我的组件时也遇到了类似的问题,我能想到的解决问题的一种方法是从
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);
})
我甚至想知道是否可以通过模拟按钮点击直接测试


让我知道这是否有帮助。

有没有一种方法可以像超时构造一样立即回调承诺?据我所知,有任何方法可以立即调用承诺回调。顺便问一下,如何立即调用超时构造?我实际上不确定我想要的是什么;像
{method,0}
这样的东西可能会使它立即返回?在JS上有很多问题,所以我只是想知道。我不认为有一种方法可以立即调用
,然后调用
。它必须经过事件循环。我已将所有API获取操作移动到一个单独的库中,该库解析、承诺并发送数据,我在组件中的方法中调用该库函数。这是因为我有一个更清晰的关注点分离和更容易模拟我的测试。
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 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' } ]
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);
})