vue.js - 如何用 Jest + Vuejs 模拟 window.location.href?
问题描述
目前,我正在为我的项目实施单元测试,并且有一个文件包含window.location.href
.
我想模拟这个来测试,这是我的示例代码:
it("method A should work correctly", () => {
const url = "http://dummy.com";
Object.defineProperty(window.location, "href", {
value: url,
writable: true
});
const data = {
id: "123",
name: null
};
window.location.href = url;
wrapper.vm.methodA(data);
expect(window.location.href).toEqual(url);
});
但我得到这个错误:
TypeError: Cannot redefine property: href
at Function.defineProperty (<anonymous>)
我尝试了一些解决方案,但没有解决。我需要一些提示来帮助我摆脱这个麻烦。请帮忙。
解决方案
你可以试试:
global.window = Object.create(window);
const url = "http://dummy.com";
Object.defineProperty(window, 'location', {
value: {
href: url
}
});
expect(window.location.href).toEqual(url);
查看该问题的 Jest Issue:
Jest Issue
推荐阅读
- php - 环境包含无效字符,它只能包含 PHP 类名中允许的字符。Symfony 4
- reactjs - 无法在 Gatsby JS 上从 GraphQL 查询超链接
- php - 在 PHP 中使用表格格式按尺寸购物
- javascript - 在 Selenium (Java) 中滚动变量 double 或 float
- sql - 无公用键连接两张表的正确方法,不匹配时保持空值
- rest - 如何将文件字节包含到 Jmeter 的 POST 请求正文中?(使用什么编码)
- sqlite - 我如何检查是否已经存在相同的标签名称?
- web-scraping - 如何从 URL 列表中提取数据以进行网络抓取
- ruby-on-rails - Ruby on Rails - Rtesseract 不适用于 Heroku
- c# - 在 ASP.NET-Core 服务中重用 MongoDB MongoClient