简体   繁体   English

开玩笑spyOn()调用实际函数,而不是模拟

[英]Jest spyOn() calls the actual function instead of the mocked

I'm testing apiMiddleware that calls its helper function callApi . 我正在测试apiMiddleware ,它调用其辅助函数callApi To prevent the call to actual callApi which will issue the API call, I mocked the function. 为了防止调用将发出API调用的实际callApi ,我对函数进行了callApi However, it still gets called. 但是,它仍然被调用。

apiMiddleware.js 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 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
  });
});

Please ignore the action's properties and argument of callApi function. 请忽略操作的属性和callApi函数的参数。 I don't think they are the concern of the point I'm trying to make. 我认为它们与我要提出的观点无关。

Tell me if you need further elaboration. 告诉我是否需要进一步阐述。

The jest mocking only works on imported functions. 开玩笑的嘲笑仅适用于导入的函数。 In your apiMiddleware.js the default function is calling callApi variable, not the "exported" callApi function. apiMiddleware.jsdefault功能是调用callApi变量,而不是“已导出”的callApi函数。 To make the mock work, move callApi into its own module, and import it in apiMiddleware.js 要使模拟工作正常,请将callApi移至其自己的模块中,然后importimport apiMiddleware.js

Good question! 好问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM