【问题标题】:Testing react app with jest and enzyme token problem用玩笑和酶令牌问题测试反应应用程序
【发布时间】:2021-02-22 11:06:45
【问题描述】:

我有一个 react 应用程序,我在其中添加了单元测试,但我的一个测试失败了,

这是我的测试文件,我想测试动作创建者getUser

当我运行npm test 时出现以下错误,

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)

我需要做什么来解决这个问题?任何想法或解决方案将不胜感激。

【问题讨论】:

    标签: javascript reactjs react-redux jestjs enzyme


    【解决方案1】:

    您收到错误Cannot read property 'getAttribute' of null,这意味着document.querySelector('meta[name="csrf-token"]') 已返回null

    为了改变你有两个选项

    1. 按照Emazaw's answer修改文档

    1. 使用jest.spyOn 监视document.querySelector 以修改其行为
    // 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')
    })
    

    【讨论】:

    • 是的,但我说过你有两个选择,所以你选择一个或另一个,而不是两个:D
    • 是的,不幸的是仍然遇到同样奇怪的错误:(ibb.co/9s0gbjL
    • @TheDeadMan 可能你必须分享api.js 的内容。我的猜测是getAttrbute 可能在导入后立即执行
    • 确实,一旦需要api.js,它就会立即被调用,因此您可以尝试添加删除import actions ....,并将其添加为const actions = require('store/actions')jest.spyOn之后的jest.spyOn
    【解决方案2】:

    嗯,简短的版本是 - 你没有在文件中使用的 DOM 元素 - 你有两个选择 - 模拟 document.querySelector 方法,以便它使用 getAttribute 方法返回对象,或者手动创建元素在 jest-dom 中,例如:

      let metaElement;
      beforeAll(() => {
        metaElement = document.createElement("meta");
        metaElement.name = "csrf-token";
        metaElement.content = "test-token";
        document.head.append(metaElement);
      })
      afterAll(() => {
        metaElement.remove();
      });
    

    我不知道您正在测试的文件代码和您使用的模拟库 (moxios) :)

    【讨论】:

    • Hej 没有解决问题 :( 不幸的是
    猜你喜欢
    • 1970-01-01
    • 2018-07-22
    • 2021-02-26
    • 2023-03-27
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 2021-01-26
    • 2020-06-21
    相关资源
    最近更新 更多