React: How to take a jest snapshot after axios fetched data

How to write React JS Jest test case to match snapshot with Axios mock implementation

Snapshot tests are a very useful tool whenever you want to make sure your UI does not change unexpectedly.

A typical snapshot test case renders a UI component, takes a snapshot, then compares it to a reference snapshot file stored alongside the test. The test will fail if the two snapshots do not match: either the change is unexpected, or the reference snapshot needs to be updated to the new version of the UI component.

Lets have look on component for Snapshot test case

import React from 'react'
import { act }  from 'react-dom/test-utils'
import { mount } from 'enzyme'
import axios from 'axios'
import { render } from '@testing-library/react'

import TestComponent from 'path-to-component' 

//mock api response here
const apiResponse = {
  fieldOne: 'One',
  fieldTwo: 'Two
}

jest.mock('axios')

//mock props if any passing to component
const props = {
 mode: client
}

describe('Test case to match snapshot', (() => {
 //In component, if you are fetching data from api then do mock implementation for that api call 
/// with mock api response
 beforeAll(() => {
  axios.get.mockImplementation(() => Promise.resolve(apiResponse)) } it('Snapshot testing', async (done) => { let component await act(async () => { component = await mount(<TestComponent {...props} />) }) expect(component.render()).toMatchSnapshot() done() } })

You may also like...