Cannot Get Jest + Typescript + Axios Test

jest-mock-axios
jest mock typescript
jest test axios interceptor
jest mock cannot find module
axios jest async
jest mock axios all
mocking axios requests in jest
nuxt jest mock axios

I have the following method in a class:

import axios from 'axios'

public async getData() {
   const resp = await axios.get(Endpoints.DATA.URL)
   return resp.data
}

Then I am trying to set up a Jest test that does this:

jest.mock('axios')

it('make api call to get data', () => {
   component.getData()
   expect(axios.get).toHaveBeenCalledWith(Endpoints.DATA.URL)
})

The problem is that because I am not mocking the return value, then it gives an error for resp.data because I'm calling data on null or undefined object. I spent at least 2 hours trying various ways to get this working but I can't find a way such that I can mock axios.get with some return value.

Jest's documentation uses JavaScript so they give this example axios.get.mockResolvedValue(resp) but I can't call mockResolvedValue because that method does not exist on axios.get in TypeScript.

Also, if you know other good testing library for React other than Jest that does this stuff easily for TypeScript, feel free to share.

In start of file:

import axios from 'axios';
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;

Now you can use it as usual mock:

mockedAxios.get.mockRejectedValue('Network error: Something went wrong');
mockedAxios.get.mockResolvedValue({ data: {} });

Cannot Get Jest + Typescript + Axios Test - reactjs - html, Cannot Get Jest + Typescript + Axios Test - reactjs. trying to set up a Jest test that does this: jest.mock('axios') it('make api call to get data', () => { component. Mocking Axios in Jest + Testing Async Functions. In our tests we don't want to perform an actual HTTP request. To start with it is slow, but there are certain calls you really can't make with every test run, for example charging someone's credit card.

If you want to use jest.mock with "no-any" try this:

import axios, { AxiosStatic } from 'axios'

interface AxiosMock extends AxiosStatic {
  mockResolvedValue: Function
  mockRejectedValue: Function
}

jest.mock('axios')
const mockAxios = axios as AxiosMock

it('make api call to get data', () => {
   // call this first
   mockAxios.mockResolvedValue(yourValue)

   component.getData()
   expect(mockAxios.get).toHaveBeenCalledWith(Endpoints.DATA.URL)
})

Axios Mocking in React using Typescript and testing-library, Tagged with typescript, axios, testing, react. In the end, it was quite simple really (the longer I get stuck on something, the easier the solution turns Here's a link to a github repo as Codesandbox doesn't support jest.mock. I found different posts that tell you how to mock Axios using Jest & Typescript. The only difference in this post is that, when I use Axios, I like to use it as a function rather than calling axios.get or axios.post. Imagine you have this Axios request that you want to mock in your tests:

but I can't call mockResolvedValue because that method does not exist on axios.get in TypeScript

You can use an assertion:

(axios.get as any).mockResolvedValue(resp)

How to mock axios in jest with Typescript, 1 min read. #Typescript #axios #jest #unit testing. This article explains the correct way how  Then we have the actual axios mock. Whenever our app sees the axios import, it'll use whatever is inside this. We're using get for this example, so I've included a get mock. The important thing to note here is that we have a default and this is used by Typescript. More info here. The Test Next, we write our test.

I found a neat solution using the sinon library npm install sinon @types/sinon --save-dev.

Then the testing code becomes:

let component: Component
let axiosStub: SinonStub

beforeAll(() => {
    component = new Component({})
    axiosStub = sinon.stub(axios, 'get')
})

afterAll(() => {
    axiosStub.restore()
})

it('make api call to get data', async () => {
    // set up behavior
    axiosStub.withArgs(Endpoints.DATA.URL).returns({data: []})

    // method under test
    const res = await component.getData()

    // assertions
    expect(res).toEqual([])
})

TypeScript and Jest: Testing Challenges, I found my holy grail of testing with TypeScript and Jest I treat axios as a mocked Jest object, and get InteliSense out of it. Of course, this code doesn't make sense logically (why would I add fromDb to a result) but for the  Promise based HTTP client for the browser and node.js - axios/axios. Promise based HTTP client for the browser and node.js - axios/axios axios / test / typescript

Mocking TypeScript classes with Jest - David Guijarro, Imagine the following scenario: you have a TypeScript class that relies on some Let's say that you want to use Jest for your unit tests, because it's quite an If you find yourself stuck at the same problem, this post might help you out a bit. the whole chain of dependencies, from the Users class to the Http class, to axios,​  However, if you look at the source code, you can see that it uses Jest only to define spies (for methods post, get, put, patch, delete, create, all, head, options, request). This means that it can easily be modified to use any other testing framework - go to GitHub , clone it, modify it, play with it :)

knee-cola/jest-mock-axios, TypeScript version of Axios mock for unit testing with [Jest](https://facebook.github​.io/jest/). MockAxios.get = jest.fn(_helperReqNoData.bind(null, "get"));. rssfrncs changed the title How to use Axios with TypeScript when using response interceptors (not AxiosResponse) How to use Axios with TypeScript when using response interceptors (AxiosResponse issue) Apr 30, 2018. rssfrncs referenced this issue Apr 30, 2018.

Mocking Axios in Jest + Testing Async Functions, To start with it is slow, but there are certain calls you really can't make… Mocking Axios in Jest + Testing Async Functions. published If you'd like to follow along you can find starter files here and a finished version here. Dismiss Join GitHub today. GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.

Comments
  • I did exactly the same thing, but typescript is blaming my { data: null } with this error: error TS2345: Argument of type '{ data: null; }' is not assignable to parameter of type '(<T = any>(url: string, config?: AxiosRequestConfig | undefined) => AxiosPromise<T>) | PromiseLike<(<T = any>(url: string, config?: AxiosRequestConfig | undefined) => AxiosPromise<T>)>'. No idea why it doesn't work...
  • you can try to type this or make any: { data: null } as any
  • This works and doesn't require another library, should be accepted answer
  • The project has a ts-lint rule "no-any": true
  • add a tslint ignore on the line before
  • 1. That's not going to be ideal as the project grows and more asynchronous calls are added. 2. I am using TypeScript for its strong type system and I don't want to circumvent it.