使用 Jest 在 JavaScript 測試 window.open()
我最近必須為開啟新瀏覽器視窗的 React 元件編寫測試。為了打開新窗口,我在程式碼中使用了 window.open() 。這使得該元件易於編寫,但我必須以不同的方式思考如何為此編寫測試。
有關 window.open() 方法的更多信息,請參閱 mdn 網路文件。
為了設定位元或背景,我有一個 React 元件,它有一個帶有幾個輸入的簡單表單。當使用者完成輸入並提交表單後,它會開啟一個指向指定 URL 的新窗口,並將輸入作為 URL 參數。
要測試的組件
這是該組件的一個非常簡化的版本作為演示。我建議使用像react-hook-form這樣的東西來為您的表單添加驗證。
// MyForm.js import React, { useState } from "react"; const MyForm = ({ baseURL }) => { const [name, setName] = useState(""); const [subject, setSubject] = useState(""); const onSubmit = () => { window.open( `${baseURL}?name=${encodeURIComponent(name)}&subject=${encodeURIComponent( subject )}`, "_blank" ); }; return ( <form onSubmit={onSubmit}> <label htmlFor="name">Name</label> <input name="name"> <p>Now we have our component, lets think about the test for it.</p> <h2> What I’d normally test </h2> <p>Normally I would test what has been rendered in my component, using assertions such as expect the component to have text content or assert the url is what is expected (using window.location.href), but I quickly realised that approach won’t work in jest for this example.</p> <p>Window.open opens a new browser window, so it doesn’t affect the component we are testing. We can’t see what is inside the new window or what its url is as it is outside of the scope of the component we are testing.</p> <p>So how do we test something that is outside of what we can see? We don’t actually need to test that a new window is opened as that would be testing the window interface’s functionality and not our code. Instead, we just need to test that the window.open method is called.</p> <h2> Mocking window.open() </h2> <p>Therefore we need to mock window.open() and test that it was called inside our code.<br> </p> <pre class="brush:php;toolbar:false">// Mock window.open global.open = jest.fn();
現在我們可以設定輸入中的值,提交表單,然後測試 window.open 是否被呼叫。我們可以使用 fireEvent 設定輸入的值並按下提交按鈕。
fireEvent.input(screen.getByLabelText("Name"), { target: { value: "Test Name", }, }); fireEvent.input(screen.getByLabelText("Subject"), { target: { value: "An example subject", }, }); fireEvent.submit( screen.getByRole("button", { name: "Submit (opens in new window)" }) );
值得閱讀文件以了解 fireEvent 的注意事項。根據您的用例,您可能想要使用使用者事件。
我們想要等待方法運行。我們可以使用 waitFor() 來做到這一點。
await waitFor(() => { expect(global.open).toHaveBeenCalled(); });
為了確保我們不會開啟大量新窗口,我們可以檢查是否只呼叫 window.open 一次。
await waitFor(() => { expect(global.open).toHaveBeenCalledTimes(1); });
我們也可以檢查呼叫該方法時使用的參數,傳入我們期望的 URL 作為第一個參數,目標作為第二個參數。
await waitFor(() => { expect(global.open).toHaveBeenCalledWith( "http://example.com?name=Test%20Name&subject=An%20example%20subject", "_blank" ); });
完整的測試文件
這是完整的測試文件供您參考。
// MyForm.test.js import React from "react"; import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import MyForm from "./MyForm"; describe("MyForm test", () => { beforeEach(() => { // Mock window.open global.open = jest.fn(); }); it("opens a new window with the correct url", async () => { render(<MyForm baseURL="http://example.com" />); fireEvent.input(screen.getByLabelText("Name"), { target: { value: "Test Name", }, }); fireEvent.input(screen.getByLabelText("Subject"), { target: { value: "An example subject", }, }); fireEvent.submit( screen.getByRole("button", { name: "Submit (opens in new window)" }) ); await waitFor(() => { expect(global.open).toHaveBeenCalled(); expect(global.open).toHaveBeenCalledTimes(1); expect(global.open).toHaveBeenCalledWith( "http://example.com?name=Test%20Name&subject=An%20example%20subject", "_blank" ); }); }); });
照片由 StockSnap 上的 energepic.com
以上是使用 Jest 在 JavaScript 測試 window.open()的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python和JavaScript開發者的薪資沒有絕對的高低,具體取決於技能和行業需求。 1.Python在數據科學和機器學習領域可能薪資更高。 2.JavaScript在前端和全棧開發中需求大,薪資也可觀。 3.影響因素包括經驗、地理位置、公司規模和特定技能。

實現視差滾動和元素動畫效果的探討本文將探討如何實現類似資生堂官網(https://www.shiseido.co.jp/sb/wonderland/)中�...

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

如何在JavaScript中將具有相同ID的數組元素合併到一個對像中?在處理數據時,我們常常會遇到需要將具有相同ID�...

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

探索前端中類似VSCode的面板拖拽調整功能的實現在前端開發中,如何實現類似於VSCode...
