如何使用Jest.fn()在Jest中使用打字稿模拟功能



我正在尝试模拟一个名为callapi的函数。我使用jest.fn(),但是我有错误消息:

函数callapi(方法:字符串,URL:字符串,路径:字符串,数据?:wos) 无法分配给" callapi",因为它是只读属性。TS(2540)

我试图遵循示例开玩笑的例子

我的代码怎么了?我为什么要有错误消息。
卡拉皮的一部分是 从" Axios"导入Axios;

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

测试如下:

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));
})

分配给 jest.fn()与打字稿键入不太合作。

使用jest.spyOn改用:

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));
})

最新更新