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

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

如果我 运行 我的 jest 测试套件有问题。 站点说明,我正在使用 vue-test-utils。 我的 Vue 数据如下所示:

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

我的元素是这样的:

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

如果我运行这个测试套件:

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

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

我收到这个错误: TypeError: Cannot read property 'content' of null

您的问题出在 meta 元素的选择上。您的选择结果为 null,因此您得到描述的 TypeErrormeta 元素并不特殊。删除访问 head 属性。

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