如何使用jest.fn()

时间:2019-03-20 11:59:45

标签: jestjs

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

  

函数callApi(方法:字符串,url:字符串,路径:字符串,数据?:任何):承诺>   无法分配“ callApi”,因为它是只读属性。ts(2540)

我尝试遵循以下示例 jest examples

我的代码有什么问题?为什么会出现错误消息。
callApi的一部分是     从“ 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));
})

1 个答案:

答案 0 :(得分:0)

分配给jest.fn()不适用于TypeScript输入。

改为使用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));
})