【问题标题】:Jest Spy says function is not calledJest Spy 说函数没有被调用
【发布时间】:2019-07-12 19:42:49
【问题描述】:

函数sendResponse 被调用,我可以判断是因为sendResponse 内的console.log 行已执行。但是,我的间谍说没有调用 sendResponse 方法。只是想知道我在这里做错了什么。

import * as ExpressHelpers from './express-helper';

describe('sendResponse', () => {
    it('sends a 500 error response', () => {
        const sendResponseSpy = spyOn(ExpressHelpers, 'sendResponse');
        const mockResponse = () => {
            const res: any = {};
            res.status = jest.fn().mockReturnValue(res);
            res.send = jest.fn().mockReturnValue(res);
            return res;
        };
        const errorMsg = 'Server error msg';
        const res = mockResponse();
        ExpressHelpers.sendServerError(errorMsg, res);
        expect(sendResponseSpy).toHaveBeenCalled();
    });
});
export function sendResponse(statusCode: HttpStatus, message: string, data: {}, response: Express.Response) {
    const responseEntity: ResponseEntity = {
        message,
        statusCode,
        data,
    };
    response.send(responseEntity);
}

export function sendServerError(serverErrorMsg: string, res: Express.Response) {
    sendResponse(HttpStatus.SERVER_ERROR, serverErrorMsg, null, res);
}

错误:

  ● Express Helper › sendResponse › sends a 500 error response

    expect(spy).toHaveBeenCalled()

    Expected spy to have been called, but it was not called.

      35 |             const res = mockResponse();
      36 |             ExpressHelpers.sendServerError(errorMsg, res);
    > 37 |             expect(sendResponseSpy).toHaveBeenCalled();
         |                                     ^
      38 |         });
      39 |     });
      40 | });

      at Object.it (src/helpers/express-helper.test.ts:37:37)

【问题讨论】:

  • 不确定我是否遵循.. 我正在监视从 sendServerError 调用的方法?除非这仅在我将间谍作为依赖项注入时才有效。
  • 抱歉,我搞不清楚它是如何工作的。我以为您创建了间谍,但随后必须手动重新分配或传递它,因此 it 被调用。我刚刚检查了文档并模拟了一个方法将它与间谍交换。
  • 是的,可能会令人困惑..所有商品:)

标签: javascript typescript jestjs


【解决方案1】:

Jest 本身并不在 ES 模块上运行,您的代码被 Babel 或 TSC 转译,然后被加载执行。这种转换的结果是您导出的函数引用现在绑定到“导出”对象,该对象在您的源代码中不可见,但存在于正在运行的代码中。

当 spyOn 被调用时,'exports' (exports.sendResponse) 对象内的引用会被监视,但函数调用 (sendResponse) 内的引用不会被监视。一种解决方案是将所有函数绑定到这样的导出对象

function foo() { namespace.bar() }
function bar() {}

const namespace = {
    foo,
    bar
}
export default namespace;

如果这感觉像是 hack,您可以使用带有静态方法的类来达到几乎相同的效果。看起来 jest 在不久的将来不会获得 ESM 支持 (https://github.com/facebook/jest/issues/4842),所以这将是更简单的解决方案之一。

【讨论】:

  • IMO 类的静态方法更干净。我刚刚使用它并且它有效。谢谢你的提示。
  • 现在是2022年,这个问题现在解决了吗?我使用的是 26.6.3 版,但仍然没有调用间谍。我不知道是我做错了还是撞到了同一堵墙。
猜你喜欢
  • 1970-01-01
  • 2016-12-23
  • 1970-01-01
  • 2021-03-06
  • 2017-09-24
  • 2017-04-02
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多