【问题标题】:How to mock a function using typescript in jest using jest.fn()如何使用 jest.fn() 在 jest 中使用 typescript 模拟函数
【发布时间】:2019-08-11 02:50:15
【问题描述】:

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

function callApi(method: string, url: string, path: string, data?: any): Promise> 无法分配给“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));
})

【问题讨论】:

    标签: jestjs


    【解决方案1】:

    分配给 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));
    })
    

    【讨论】:

    • 我遇到错误超时 - 在 jasmine.DEFAULT_TIMEOUT_INTERVAL 指定的超时内未调用异步回调。在 pTimeout (node_modules/jest-jasmine2/build/queueRunner.js:53:21) 在 Timeout.callback [as _onTimeout] (node_modules/jsdom/lib/jsdom/browser/Window.js:523:19)
    • @jupitersailormoon 这是一个单独的问题(听起来您的传奇可能无法解决),如果需要帮助,应该在新问题中解决。
    • 我已经添加了完成功能。感谢stackoverflow.com/questions/49603939/… 并感谢@brian-lives-outdoors
    • 经过数小时的搜索,这个答案让我免于将键盘从办公桌上摔下来。谢谢!
    猜你喜欢
    • 2017-12-19
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 2020-02-26
    • 2018-07-23
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多