Reactjs 使用URL对象进行Jest测试
我有一个例子,我的代码使用URL api,创建如下:Reactjs 使用URL对象进行Jest测试,reactjs,testing,url,mocking,jestjs,Reactjs,Testing,Url,Mocking,Jestjs,我有一个例子,我的代码使用URL api,创建如下: const\u url=新url(window.location.href) 这样使用: if (_url.searchParams.get('locale')) { do something } 然而,在我的玩笑测试中,我得到了一个错误: TypeError:无法读取未定义的属性“get” 我在安装文件中尝试了全局模拟: global.URL = jest.fn(() => { return { searchPa
const\u url=新url(window.location.href)代码>
这样使用:
if (_url.searchParams.get('locale')) {
do something
}
然而,在我的玩笑测试中,我得到了一个错误:
TypeError:无法读取未定义的属性“get”
我在安装文件中尝试了全局模拟:
global.URL = jest.fn(() => {
return {
searchParams: jest.fn(() => {
return {
get: jest.fn(() => {
return '';
}),
};
}),
};
});
但它似乎不起作用。查看my\u url
对象的控制台日志输出,它似乎同时缺少searchParam属性:
URL {
[Symbol(impl)]: URLImpl {
_url: {
scheme: 'http',
username: '',
password: '',
host: 'localhost',
port: null,
path: [Array],
query: null,
fragment: null,
cannotBeABaseURL: false
},
[Symbol(wrapper)]: [Circular]
}
}
我做错了什么?我可以通过在设置文件中进行全局模拟来解决它,如下所示:
global.URL = (() => {
return {
searchParams: {
get: jest.fn((param) => {
const reg = `[?&]${param}=([^&]*)`;
return (window.location.search.match(reg) && window.location.search.match(reg)[1]) ? window.location.search.match(reg)[1] : '';
}),
},
};
});
为了避免单元测试错误,可以使用try{}catch(e){}
块,默认值如下:
const myFunction = url => {
try {
return new URL(url).hostname;
} catch (e) {
console.warn('new URL(...) object is not supported');
}
return {};
}