React: Mock axios and request.post in jest

CategoriesJavaScript, Node & React

I spent quite a bit of time on this yesterday, but here it is. A simple test that mocks the request.post. The mocked method is in another module, so this is an example of mocking modules also.


// ./shared/request.jsx

import axios from "axios"

export default axios.create({})

// ./jwt_manager/index.test.jsx

import Adapter from "enzyme-adapter-react-16"
import * as enzyme from "enzyme"
import { mount, shallow } from "enzyme"
import React, { useState } from "react"
import { act } from '@testing-library/react'

import { JwtContextProvider, LoginWithPassword } from "."
import { logg, request } from "../shared"

enzyme.configure({ adapter: new Adapter() })

describe("LoginWithPassword", () => {

  beforeEach(() => {
    jest.spyOn(request, 'post').mockResolvedValue({ data: { some: 'dataz' } })
  })

  it("submits on Enter", async () => {
    let component = mount(
      
    )
    expect(component.find('input[type="password"]').length).toEqual(1)

    component.find('input[type="password"]').simulate('keydown', { key: 'Enter' })
    await act(() => new Promise(setImmediate))

    expect(request.post).toHaveBeenCalled()
  })

})


// what is being tested,
// ./jwt_manager/index.jsx

...

  const doPasswordLogin = async (email, password) => {
    request.post(`${config.apiOrigin}${config.routes.loginWithPasswordPath}`, { email, password }
    ).then((r) => r.data
    ).then((resp) => {
      localStorage.setItem(C.jwt_token, resp.jwt_token)
    }).catch((e) => {
      logg(e, 'e322')
      toast("Login failed")
      setCurrentUser(C.anonUser)
    })
  }

...

Leave a Reply