在axios提取componentDidMount中的数据之后,如何制作一个开玩笑的快照? [英] How to take a jest snapshot after axios fetched data in componentDidMount?

查看:239
本文介绍了在axios提取componentDidMount中的数据之后,如何制作一个开玩笑的快照?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要测试的组件

class Carousel extends React.Component {
  state = {
    slides: null
  }

  componentDidMount = () => {
    axios.get("https://s3.amazonaws.com/rainfo/slider/data.json").then(res => {
      this.setState({ slides: res.data })
    })
  }

  render() {
    if (!slides) {
      return null
    }

    return (
      <div className="slick-carousel">
        ... markup trancated for bravity
      </div>
    )
  }
}

export default Carousel

测试

import React from "react"
import renderer from "react-test-renderer"
import axios from "axios"
import Carousel from "./Carousel"

const slides = [
  {
    ID: "114",
    REFERENCE_DATE: "2018-07-02",
    ...
  },
  {
    ID: "112",
    REFERENCE_DATE: "2018-07-06",
    ...
  },
  ...
]

jest.mock("axios")

it("", () => {
  axios.get.mockImplementationOnce(() => Promise.resolve({ data: slides }))

  const tree = renderer.create(<Carousel />).toJSON()
  expect(tree).toMatchSnapshot()
})

快照仅记录null,因为在执行时,我认为state.slides = null.

snapshot only records null, since at the moment of execution I suppose state.slides = null.

在axios提取数据后,我不能专心于如何实现期望.

Can't put my finger on how to run expectations after axios done fetching the data.

大多数在线样品要么使用酶,要么显示具有返回诺言的异步功能的测试.我找不到仅使用笑话和渲染组件显示示例的示例.

Most of the samples online either use enzyme, or show tests with async functions that return promises. I couldn't find one that would show example only using jest and rendered component.

我尝试过使用done回调来制作测试函数async,但是没有运气.

I tried making test function async, also using done callback, but no luck.

推荐答案

简而言之:

it("", async () => {
  axios.get.mockImplementationOnce(() => Promise.resolve({ data: slides }))

  const tree = renderer.create(<Carousel />);
  await Promise.resolve();
  expect(tree.toJSON()).toMatchSnapshot()
})

应该做这份工作

详细信息:除了您已经模拟了对API数据的调用之外,仍然以异步方式进行.因此,我们需要toMatchSnapshot调用转到微任务队列的末尾. setTimeout(..., 0)setImmediate也可以使用,但是我发现await Promise.resolve()更好地被识别为下面的所有内容都将排在队列末尾"

in details: besides you have mocked call to API data is still coming in async way. So we need toMatchSnapshot call goes to end of microtasks' queue. setTimeout(..., 0) or setImmediate will work too but I've found await Promise.resolve() being better recognizable as "everything below is coming to end of queue"

[UPD]固定代码段:.toJSON必须在等待之后,它返回的对象将永远不会更新

[UPD] fixed snippet: .toJSON must be after awaiting, object it returns will never be updated

这篇关于在axios提取componentDidMount中的数据之后,如何制作一个开玩笑的快照?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆