jupiter sailormoon
jupiter sailormoon

Reputation: 301

How to mock a function using typescript in jest using jest.fn()

I am trying to mock a function named callApi. I use jest.fn(), but I am having the error message:

function callApi(method: string, url: string, path: string, data?: any): Promise> Cannot assign to 'callApi' because it is a read-only property.ts(2540)

I have tried to follow the examples on jest examples

What is wrong with my code? Why am I having the error message.
Part of callApi is import axios from "axios";

export function callApi(
  method: string,
  url: string,
  path: string,
  data?: any
) {
  switch (method) {

The test is as follows:

import {runSaga} from 'redux-saga';
import * as api from '../Utilities/api'
import { getPaymentsError, getPaymentsSuccess, IPaymentsAction } from './actions';
import handleFetch from './sagas'


test('should test fetch payments success',async() =>{
const dispatchedActions = [{}];
const mockedPayments = [{
    details: {
    amount: "10000",
    date: new Date(),
    id: 5
  },
  id: 5,
  month: "Feb 2003",
  userID: 3
}];


 api.callApi = jest.fn(() => Promise.resolve(mockedPayments));<----------error here



const fakeStore = {
    dispatch:(action:IPaymentsAction) =>dispatchedActions.push(action)
}
await runSaga(fakeStore,handleFetch).done;
expect(api.callApi.mock.calls.length).toBe(1);
expect(dispatchedActions).toContainEqual(getPaymentsSuccess(mockedPayments));
})

Upvotes: 0

Views: 3991

Answers (1)

Brian Adams
Brian Adams

Reputation: 45810

Assigning to a jest.fn() doesn't work well with TypeScript typing.

Use jest.spyOn instead:

test('should test fetch payments success', async (done) => {
  const dispatchedActions = [{}];
  const mockedPayments = [{
    details: {
      amount: "10000",
      date: new Date(),
      id: 5
    },
    id: 5,
    month: "Feb 2003",
    userID: 3
  }];

  const spy = jest.spyOn(api, 'callApi');
  spy.mockImplementation(() => Promise.resolve(mockedPayments));

  const fakeStore = {
    dispatch: (action: IPaymentsAction) => dispatchedActions.push(action)
  }
  await runSaga(fakeStore, handleFetch);done();
  expect(spy.mock.calls.length).toBe(1);
  expect(dispatchedActions).toContainEqual(getPaymentsSuccess(mockedPayments));
})

Upvotes: 4

Related Questions