Javascript 在jest内调用时返回undefined的函数,以便调用
我有一个简单的测试,将检查我们的内部Javascript 在jest内调用时返回undefined的函数,以便调用,javascript,reactjs,testing,jestjs,react-testing-library,Javascript,Reactjs,Testing,Jestjs,React Testing Library,我有一个简单的测试,将检查我们的内部记录器功能的输出,并确保它使用正确的参数/输出运行 问题是,在调用logger的responseInterceptorResponse函数中,我有另一个正在运行的函数:getSourceURL当在这些测试中使用时,此函数返回未定义的。我不知道为什么 我想它解决了我在模拟/utils/logger函数这一事实。所以没有什么getSourceURL是什么的上下文,也没有什么将任何信息传递给它的上下文 测验 getSourceURL 应答器应答器应答器 测试输出:
记录器
功能的输出,并确保它使用正确的参数/输出运行
问题是,在调用logger
的responseInterceptorResponse
函数中,我有另一个正在运行的函数:getSourceURL
当在这些测试中使用时,此函数返回未定义的
。我不知道为什么
我想它解决了我在模拟/utils/logger
函数这一事实。所以没有什么getSourceURL
是什么的上下文,也没有什么将任何信息传递给它的上下文
测验
getSourceURL
应答器应答器应答器
测试输出:
import { logger } from '@server/utils/logger';
import { responseInterceptorResponse, requestInterceptor } from './interceptors';
jest.mock('axios');
jest.mock('@server/utils/logger');
describe('responseInterceptorResponse', () => {
it('Should log if it is on the server', () =>
const req = {
headers: {
host: 'localhost:3000',
referer: 'https://localhost:3000/',
},
reqPath: '/women',
};
responseInterceptorResponse({}, {}, req);
expect(logger).toHaveBeenCalledWith(
'Request Response - Time: NaNms - Status: - Response: {}, source url: https://localhost:3000/women',
'I',
'standard',
);
});
});
const getSourceURL = (req, path = '') => {
const protocol = getProtocol(req);
const urlPath = path === '' && (req && typeof req?.reqPath !== "undefined") ? req?.reqPath : path
if(!protocol) return ', missing source url'
return `, source url: ${protocol}://${req.headers.host}${urlPath}`
}
module.exports = {
logger,
logAccess,
getSourceURL,
};
export const responseInterceptorResponse = (response, res, req) => {
if (typeof window === 'undefined') {
const endTime = Date.now();
const duration = endTime - response?.config?.startTime;
const status = response?.status || '';
const url = response?.config?.url || '';
const data = response?.data?.data || response?.data || {};
const sourceURL = getSourceURL(req); //returning undefined...
logger(
`Request Response - Time: ${duration}ms - Status: ${status} ${url} - Response: ${JSON.stringify(
data,
)}${sourceURL}`,
'I',
'standard',
);
}
return response;
};
Error: expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: "Request Response - Time: NaNms - Status: - Response: {}, source url: https://localhost:3000/women", "I", "standard"
Received: "Request Response - Time: NaNms - Status: - Response: {}undefined", "I", "standard"
Number of calls: 1