【问题标题】:Expected mock function to have been called with. But it was not called. Jest预期的模拟函数已被调用。但它没有被调用。笑话
【发布时间】:2017-09-09 18:02:03
【问题描述】:

我想用jest 测试以下函数。

import * as pointsAwardingApi from '../api/pointsAwardingApi';
export function awardPoints(pointsAwarding) {
  return function (dispatch) {
    return new Promise((resolve, reject) => {
      pointsAwardingApi.awardPoints(pointsAwarding);
    });
  };
}

然后,我创建了以下测试。

import * as pointsAwardingApi from '../../../src/api/pointsAwardingApi';
it("should call award points api", () => {
  //given
  pointsAwardingApi.awardPoints = jest.fn();
  let dispatcher = pointsAwardingActions.awardPoints({phone: '555'});

  //when
  dispatcher(mockedDispatch);

  //then
  expect(pointsAwardingApi.awardPoints).toBeCalledWith({phone: '555'});
});

但是,当我运行测试时,出现以下错误。

expect(jest.fn()).toBeCalledWith(expected)
Expected mock function to have been called with: [{"phone": "555"}]
But it was not called.

我猜这是Promise 的问题,但我不知道如何解决。

【问题讨论】:

    标签: javascript testing promise jestjs


    【解决方案1】:

    我意识到我错过了在对象上添加spy

    jest.spyOn(pointsAwardingApi, 'awardPoints');
    

    【讨论】:

    • 我很难理解 spyOn 如何在 atm 工作。你在哪个对象上添加了这个?
    • 您只需将您想要的对象和函数作为参数传递给spy。然后你可以调用expect 传递该函数并检查它是否是使用toBeCalledWith 调用的。看看上面的问题。
    猜你喜欢
    • 2018-12-27
    • 2019-03-28
    • 2019-10-27
    • 2019-03-23
    • 1970-01-01
    • 2019-07-03
    • 2018-05-25
    • 1970-01-01
    • 2017-11-17
    相关资源
    最近更新 更多