chenxiaochun / blog

🖋️ChenXiaoChun's blog
179 stars 15 forks source link

jest 踩坑记录 #64

Open chenxiaochun opened 5 years ago

chenxiaochun commented 5 years ago

错误异常一

当运行单元测试时,如果抛出了下面的异常。说明你的代码中使用了window.location.href,而在 jsdom 环境中并没有location这个对象,所以就抛出了异常。

Error: Not implemented: navigation (except hash changes)

解决办法就是将你源代码中的window.location.href替换成window.location.assign(url)。然后在单元测试中使用jest.spyOn(window.location, 'assign').mockImplementation(() => jest.fn())来 mock 这个方法即可解决问题。具体详情可参考 #2112