Jest spyOn()调用实际函数而不是模拟函数

问题描述 投票:2回答:1

我正在测试调用它的辅助函数apiMiddlewarecallApi。为了防止调用将发出API调用的实际callApi,我模拟了该函数。但是,它仍然被调用。

apiMiddleware.js

import axios from 'axios';

export const CALL_API = 'Call API';

export const callApi = (...arg) => {
  return axios(...arg)
    .then( /*handle success*/ )
    .catch( /*handle error*/ );
};

export default store => next => action => {
  // determine whether to execute this middleware
  const callAPI = action[CALL_API];
  if (typeof callAPI === 'undefined') {
    return next(action)
  }

  return callAPI(...callAPI)
    .then( /*handle success*/ )
    .catch( /*handle error*/ );
}

apiMiddleware.spec.js

import * as apiMiddleware from './apiMiddleware';

const { CALL_API, default: middleware, callApi } = apiMiddleware;

describe('Api Middleware', () => {

  const store = {getState: jest.fn()};
  const next = jest.fn();
  let action;

  beforeEach(() => {
    // clear the result of the previous calls
    next.mockClear();
    // action that trigger apiMiddleware
    action = {
      [CALL_API]: {
        // list of properties that change from test to test 
      }
    };
  });

  it('calls mocked version of `callApi', () => {
    const callApi = jest.spyOn(apiMiddleware, 'callApi').mockReturnValue(Promise.resolve());

    // error point: middleware() calls the actual `callApi()` 
    middleware(store)(next)(action);

    // assertion
  });
});

请忽略callApi函数的动作属性和参数。我不认为他们是我想要的关注点。

告诉我你是否需要进一步阐述。

javascript mocking jestjs redux-middleware
1个回答
3
投票

jest mocking仅适用于导入的函数。在你的apiMiddleware.js中,default函数调用callApi变量,而不是“导出的”callApi函数。要使模拟工作,将callApi移动到自己的模块中,并将import移动到apiMiddleware.js

好问题!

© www.soinside.com 2019 - 2024. All rights reserved.