简体   繁体   English

用笑话和酶标记问题测试反应应用程序

[英]Testing react app with jest and enzyme token problem

I have a react app in which I have added unit testing, but one of my tests fails,我有一个 React 应用程序,我在其中添加了单元测试,但是我的一个测试失败了,

Here is my test file, I want to test action creators getUser .这是我的测试文件,我想测试动作创建者getUser

在此处输入图片说明

When I run npm test I get the following error,当我运行npm test ,出现以下错误,

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.任何想法或解决方案将不胜感激。

Well, short version is - you don't have a DOM element which you use in your file - you have two options - mocking document.querySelector method, so that it return object with getAttribute method, or creating element manually in jest-dom, like:嗯,简短的版本是 - 你没有在你的文件中使用的 DOM 元素 - 你有两个选择 - 模拟document.querySelector方法,以便它使用getAttribute方法返回对象,或者在 jest-dom 中手动创建元素,喜欢:

  let metaElement;
  beforeAll(() => {
    metaElement = document.createElement("meta");
    metaElement.name = "csrf-token";
    metaElement.content = "test-token";
    document.head.append(metaElement);
  })
  afterAll(() => {
    metaElement.remove();
  });

I don't know however both code of file you're testing, and mocking library you use ( moxios ) :)但是,我不知道您正在测试的文件代码和您使用的moxios库( moxios ):)

You get the error Cannot read property 'getAttribute' of null , which means that document.querySelector('meta[name="csrf-token"]') have returned null .您收到错误Cannot read property 'getAttribute' of null ,这意味着document.querySelector('meta[name="csrf-token"]')已返回null

In order to change that you have two options :为了改变你有两个选择

  1. Modify the document as per Emazaw's answer根据Emazaw 的回答修改文档

OR或者

  1. Use jest.spyOn to spy on document.querySelector to modify it's behaviour使用jest.spyOn监视document.querySelector以修改其行为
// 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')
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM