测试带有笑话和酶令牌问题的应用程序反应 [英] Testing react app with jest and enzyme token problem
本文介绍了测试带有笑话和酶令牌问题的应用程序反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个React应用,其中添加了单元测试,但是我的一项测试失败了,
I have a react app in which I have added unit testing, but one of my tests fails,
这是我的测试文件,我想测试动作创建者getUser
.
Here is my test file, I want to test action creators getUser
.
当我运行npm test
时,出现以下错误,
When I run npm test
I get the following error,
FAIL UnitTests resources/js/tests/actions/index.test.js
● Test suite failed to run
TypeError: Cannot read property 'getAttribute' of null
8 | 'Accept': 'application/json',
9 | 'Content-Type': 'application/json',
> 10 | 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
| ^
11 | },
12 | });
13 |
at Object.<anonymous> (utils/api.js:10:19)
at Object.<anonymous> (store/actions/userActions.js:2:1)
at Object.<anonymous> (store/actions/index.js:2:1)
at Object.<anonymous> (tests/actions/index.test.js:3:1)
我需要怎么做才能解决此问题?任何想法或解决方案将不胜感激.
What do I need to do to solve this problem? any idea or solution will be appreciated.
推荐答案
您会收到错误Cannot read property 'getAttribute' of null
,表示document.querySelector('meta[name="csrf-token"]')
已返回null
.
You get the error Cannot read property 'getAttribute' of null
, which means that document.querySelector('meta[name="csrf-token"]')
have returned null
.
要更改,您有两个选项:
- 根据 Emazaw的答案 修改文档
- Modify the document as per Emazaw's answer
OR
- 使用
jest.spyOn
监视document.querySelector
来更改其行为
- Use
jest.spyOn
to spy ondocument.querySelector
to modify it's behaviour
// this should be called before attempting to read the meta's attribute
jest.spyOn(document, 'querySelector').mockReturnValue({
getAttribute: jest.fn().mockReturnValue('MOCK-CSRF-TOKEN-VALUE')
})
这篇关于测试带有笑话和酶令牌问题的应用程序反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文