Testing react app with jest and enzyme token problem

偶尔善良 提交于 2020-12-15 07:19:16

问题


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.


回答1:


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




回答2:


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')
})


来源:https://stackoverflow.com/questions/64770117/testing-react-app-with-jest-and-enzyme-token-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!