簡體   English   中英

用笑話和酶標記問題測試反應應用程序

[英]Testing react app with jest and enzyme token problem

我有一個 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)

我需要做什么來解決這個問題? 任何想法或解決方案將不勝感激。

嗯,簡短的版本是 - 你沒有在你的文件中使用的 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庫( moxios ):)

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

為了改變你有兩個選擇

  1. 根據Emazaw 的回答修改文檔

或者

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM