【问题标题】:Jest spyOn() calls the actual function instead of the mockedJest spyOn() 调用实际函数而不是模拟函数
【发布时间】:2022-03-26 08:30:01
【问题描述】:

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

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】:

    开玩笑的模拟仅适用于导入的函数。在您的 apiMiddleware.js 中,default 函数正在调用 callApi 变量,而不是“导出的”callApi 函数。为了使模拟工作,将callApi 移动到它自己的模块中,并将import 移动到apiMiddleware.js

    好问题!

    【讨论】:

      【解决方案2】:

      我解决了将代码转换为Class 的问题,例如:

      // Implementation 
      export class Location {
        getLocation() {
          const environment = this.getEnvironmentVariable();
          return environment === "1" ? "USA" : "GLOBAL";
        }
        getEnvironmentVariable() {
          return process.env.REACT_APP_LOCATION;
        }
      }
      
      
      // Test
      import { Location } from "./config";
      
      test('location', () => {
        const config = new Location();
        jest.spyOn(config, "getEnvironmentVariable").mockReturnValue("1")
      
        const location = config.getLocation();
        expect(location).toBe("USA");
      });
      

      【讨论】:

        猜你喜欢
        • 2021-05-23
        • 2019-07-14
        • 2017-11-29
        • 2021-11-03
        • 1970-01-01
        • 2021-08-21
        • 2023-03-04
        • 2019-03-22
        • 1970-01-01
        相关资源
        最近更新 更多