首页 > 解决方案 > 匹配器错误:接收到的值必须是模拟或间谍函数 - 值未定义

问题描述

错误就在身边getSourceURL,并且能够模拟它的响应,因为它是在内部调用中调用的logger

import { logger, getSourceURL } from '@server/utils/logger';

jest.mock('@server/utils/logger', () => ({
  getSourceURL: jest.fn()
}));

getSourceURL.mockReturnValue('https://localhost:3000/women')

jest.js

describe('Has Error Response', () => {
  it('Should log an error message', () => {
    expect(logger).toHaveBeenCalledWith(
      `Response Error - Time: NaNms - response status: ${status}`
    );
  });
});

/utiles/logger

const getSourceURL = (req, path = '') => {
  const protocol = getProtocol(req);
  const urlPath = path === '' && req && typeof req?.reqPath !== 'undefined' ? req?.reqPath : path;
  return printSourceURL(`${protocol}://${req.headers.host}${urlPath}`);
};
const logger = (message, severity = 'I') => {
  const output = `${getDateTime()} ${process.pid} ${severity} ${message}\n`;
  console.log(output);
};
const logAccess = (req, res, timeTaken) => {
  const output = 'something'
  logger(output, 'A');
  return output;
};

开玩笑的错误:

Error: expect(received).toHaveBeenCalledWith(...expected)

Matcher error: received value must be a mock or spy function

Received has value: undefined

标签: javascriptnode.jsjestjs

解决方案


推荐阅读