The Dead Man
The Dead Man

Reputation: 5566

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.

enter image description here

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.

Upvotes: 1

Views: 1047

Answers (2)

Teneff
Teneff

Reputation: 32158

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

Upvotes: 3

Emzaw
Emzaw

Reputation: 758

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

Upvotes: 3

Related Questions