Testing components in React Native using asynchronous Jest methods

I have a component that triggers a fetch request when it mounts and then displays the results.

I've been struggling to create a test snapshot of this component after the request is completed. I've searched on various forums like SO but haven't found a solution yet. Here are some related questions on SO that were not helpful:

  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?

Here's the mock of my 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))
}

The simplified version of the component:

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
    }

Here's the test I'm running:

    test("view renders correctly", async done => {
        fetch.mockResponseSuccess(
            JSON.stringify({
                data: [
                    { caption: "test", likes: 100 },
                    { caption: "test2", likes: 200 }
                ]
            })
        )
        
        const wrapper = await shallow(<Posts />) 
        expect(wrapper).toMatchSnapshot()
        done()
    })

The problem is that even after the fetch request completes, this.state.items in the snapshot remains empty.

Answer №1

Here is how I managed to resolve this issue for my own reference:

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

        done()
    })
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to make a view go fullscreen in React Native

I am attempting to create a similar animation (the pesto bruschetta) as this one. Within my listView, I have multiple cards with specific dimensions. When clicked, I want one of the cards to expand into fullscreen, displaying additional information. My c ...

What's the rationale behind receiving the second before the first?

I've been digging into ES6 promises, and I thought I had a handle on it for a moment. However, it seems like I may have hit a roadblock. What I'm aiming to do is handle a series of file operations where each operation depends on the completion o ...

Displaying an array of JSON objects in ReactJS by parsing them

Recently, I've encountered an odd issue with my React App. I am attempting to parse a JSON object that includes arrays of data. The structure of the data looks something like this: {"Place":"San Francisco","Country":"USA", "Author":{"Name":"xyz", "Ti ...

Accessing data stored in XML or JSON files from a local server

I am currently working on loading a list of coordinates for a Google map from either an XML or JSON file, both of which are hosted in the same directory on my local test server. So far, I have used a hard-coded JSON object to load map coordinates for tes ...

Using maxCDN to deliver static files within a Node application

Our current project is built using keystone and nunjucks, with all paths to static files following the format /stc/img/someimage.jpg. I am looking for a way to serve these files through middleware in our node server from maxCDN. Is there a solution that ...

Strategies for creating a dynamic progress bar using jQuery and JavaScript

I'm currently working on a project that involves increasing a percentage number while filling up the background color inside it based on the percentage value. The current setup is functional in terms of animating the background, but I need it to dynam ...

Combine several JSON files into a single file

After spending countless hours searching on Google, I finally gathered the courage to ask my question here. I have several json files. localhost/feed01.json localhost/feed02.json localhost/feed03.json All of the json file structures are similar to this ...

unique navbar color transition effect specifically for the homepage

I have successfully created a function called changeColour in my code that changes the color of the navbar when scrolling past a certain point. However, I am encountering an issue where I only want this effect to be applied on the Home page. I would like a ...

What is the method for initiating a radial gradient from the middle of the pie chart?

In my pie chart with grid lines, I have successfully implemented a radial gradient. However, the issue is that there is a separate gradient for each pie slice. What I really want is a single gradient originating from the center of the entire pie chart. I ...

The json_encode function in Javascript is not returning a valid value

I am facing an issue with a PHP array that I encode using json_encode and then pass to a variable in a JavaScript function. Even though the array seems fine after encoding, it appears as a valid JavaScript array. However, I keep receiving 'undefined&a ...

angular2 and ionic2 encounter issues when handling requests with observable and promises

I am attempting to trigger an action once a promise request has been resolved, but I'm having trouble figuring out how to achieve this. After doing some research, I learned that Ionic2 storage.get() returns a promise, and I would like to make an HTTP ...

Issue with React Routes only occurring in the production website

I'm encountering an issue on my personal website that only occurs in production, but not in my local environment. Here's the situation: I have set up the routes as follows const Routes = () => ( <Router> <Route exact path=&quo ...

Using AJAX to send data to the server in jQuery

Currently, I have an AJAX request implemented on my webpage. I am exploring methods to detect when an AJAX call is initiated within the page using jQuery or JavaScript. Is there a way to identify or trigger a function upon the initiation of an AJAX reques ...

Issue encountered while importing dependency in Cypress Cucumber framework

Currently facing an issue with importing certain dependencies in Cucumber. The error message I received is as follows: Running: features\my_feature.feature... (1 of 1) Browserslist: caniuse-lite is outdated. P ...

Assigning object properties from a request to every item in an observable array of objects using RxJS

Despite my efforts to search various resources like mergeMap and switchMap, I am unable to solve the problem I'm facing as I am still new to RxJs. While I would like to provide more details about my attempts in this post, I fear it may complicate my q ...

Tips for testing views in ember.js using unit tests

We are currently delving into the world of Ember.js. Our development process is completely test-driven, and we aim to apply the same methodology to Ember.js. Having prior experience in test-driven development with Backbone.js apps using Jasmine or Mocha/Ch ...

Testing abstract class methods in Jest can ensure full coverage

In my project, I have an abstract generic service class. export default abstract class GenericService<Type> implements CrudService<Type> { private readonly modifiedUrl: URL; public constructor(url: string) { this.modifiedUrl = ...

Is there a way to integrate jQuery and Javascript into a Firefox add-on?

Having trouble creating a new element on the page? After checking both the page and domain during onload, it seems that everything is in order. But how can you successfully create a new element in the correct window page? window.addEventListener("load", f ...

What is the best way to add a new item to an object using its index value?

Can the Locations object have a new property added to it? The property to be added is: 2:{ name: "Japan", lat: 36, lng: 138, description: 'default', color: 'default', url: 'default' } The current Location ...

Encountering a 500 error while trying to access a different file using the .get()

My current project involves setting up basic Express routing. However, every time I try to fetch data in order to link to a new page on my website, I encounter a 500 error. The main file managing the routing is Index.js. The content of Index.js: var expr ...