Skip to content Skip to sidebar Skip to footer

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 follo

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

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

Post a Comment for "Testing React App With Jest And Enzyme Token Problem"