javascript - React Native 异步 Jest 组件测试

标签 javascript react-native asynchronous testing jestjs

我有一个组件在装载时分派(dispatch) fetch 请求,并显示结果。

我正尝试在请求完成后创建此组件的测试快照。很长一段时间以来,我一直在努力解决这个问题,这里是关于 SO 的相关问题,但我没有运气:

  1. Async component snapshot using Jest and Redux
  2. How do test async components with Jest?
  3. React+Jest - Testing async components and waiting for mount
  4. How to take a jest snapshot after axios fetched data in componentDidMount?

这是我的fetch 模拟:

// Mocking the global.fetch included in React Native
global.fetch = jest.fn()

// Helper to mock a success response (only once)
fetch.mockResponseSuccess = (body, status = 200) => {
    fetch.mockImplementationOnce(() =>
        Promise.resolve({
            status,
            json: () => Promise.resolve(JSON.parse(body))
        })
    )
}

// Helper to mock a failure response (only once)
fetch.mockResponseFailure = error => {
    fetch.mockImplementationOnce(() => Promise.reject(error))
}

组件(简化):

export class Posts extends Component {
    constructor(props) {
        super(props)
        this.state = {
            items: [],
            loading: false
        }
        this._getItems()
    }

    async _getItems() {
        const resp = await fetch(
                "/user/recent_posts",
                {
                    method: "GET"
                }
            )
        this.setState({
            items: resp.json["data"],
        })
    }

    render() {
        // renders this.state.items
    }

这是测试:

    test("view renders correctly", async done => {
        fetch.mockResponseSuccess(
            JSON.stringify({
                data: [
                    { caption: "test", likes: 100 },
                    { caption: "test2", likes: 200 }
                ]
            })
        )
        // also tried with setTimeout and setImidiate
        const wrapper = await shallow(<Posts />) // also tried with react-test-renderer
        await wrapper.update() // didn't work with or without
        // await waitForState(wrapper, state => state.loading === false) --> didn't work
        // process.nextTick(() => {.... --> didn't work
        // jest.runTimersToTime(1) --> didn't work
        expect(wrapper).toMatchSnapshot()
        done()
    })

问题是快照中的this.state.items总是空的。

最佳答案

为了将来引用,以下是为我解决的问题:

test("view renders correctly", done => {
    // mock response here...
    const wrapper = shallow(<Posts />)
    setImmediate(() => {
        wrapper.update()
        try {
            expect(wrapper).toMatchSnapshot()
        } catch (e) {
            console.log(e)
        }

        done()
    })
})

关于javascript - React Native 异步 Jest 组件测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56627456/

相关文章:

javascript - Chrome 扩展 - 从上下文菜单访问 chrome.devtools.inspectedWindow

javascript - React - 异步等待异步问题

html - 在javascript中更改下载名称

javascript - jQCloud 如何使用 fontsize 属性作为函数

javascript - react 导航 : styling TabNavigator text

javascript - 上标 React-Native 文本

ios - 使用 react-native 和 expo 为 iOS 应用程序设置不同的语言

asynchronous - Flutter : Failed assertion: line 146: '<optimized out>' : is not true 中的 Dart future 问题

javascript - 将回调直接排队到事件队列中

javascript - React Native 将参数传递给导航器