Search code examples
javascriptvue.jsjestjsvue-test-utils

"TypeError: Cannot read property 'content' of null" Running in Jest


I have a problem if I run my jest test suite. Site note, I'm using vue-test-utils. My vue data looking like this:

data() {
    return {
      token: document.head.querySelector('meta[name="csrf-token"]'),
    };
  },

My element is this:

<input
          type="hidden"
          name="_token"
          :value="token.content"
        >

If I run this test suite:

beforeEach(() => {
    const csrfToken = 'mocked-csrf-token';
    document.head.innerHTML = `<meta name="csrf-token" content="${csrfToken}">`;

    wrapper = shallowMount(NavbarDropdownProfileFooter, { attachToDocument: true });
  });

I get this error: TypeError: Cannot read property 'content' of null


Solution

  • Your issue lies at the selection of the meta element. Your selection results in null, therefore you get the described TypeError. meta elements are not special. Remove accessing the head prop.

    document.querySelector('meta[name="csrf-token"]')