简体   繁体   中英

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,

Here is my test file, I want to test action creators getUser .

在此处输入图片说明

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.

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:

  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 ) :)

You get the error Cannot read property 'getAttribute' of null , which means that document.querySelector('meta[name="csrf-token"]') have returned null .

In order to change that you have two options :

  1. Modify the document as per Emazaw's answer

OR

  1. Use jest.spyOn to spy on document.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')
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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