title: mocking a conditional window.open function call with jest
body: <p>I am trying to write a test to make sure that, when and when i pass a valid URL arg to a function it runs <code>windows.open(args)</code> to open it. then to make sure that i focus on it.</p>
  
  <p><strong>Test link validity:</strong></p>
  
  <pre><code>export function isValidURL(url: string): boolean {
    try {
      new URL(url)
      return true
    } catch (e) {
      console.warn(`Invalid URL: ${url}`)
      return false
    }
  }
  </code></pre>
  
  <p><strong>Open link:</strong></p>
  
  <pre><code>export function openURL(url: string): void {
    if (isValidURL(url)) {
      const exTab = window.open(url, "_blank")
      if (exTab) exTab.focus()
    }
  }
  </code></pre>
  
  <p>I thinked that i should mock some function or maybe to fake it's code, then wait for it's number of call or something like that. but i'm new with jest and testing and i feel so confused of how that can be done.</p>
  
  <p><strong>My issay:</strong></p>
  
  <pre><code>describe("Test tools.openURL()", () =&gt; {
    test("it should open link if valid.", () =&gt; {
      const { open } = window
      delete window.open
      window.open = jest.fn()
      openURL("htts//url2.de9v")
      expect(window.open).not.toHaveBeenCalled()
      openURL("https://www.url1.dev")
      expect(window.open).toHaveBeenCalled()
      window.open = open
      // test focus here
    })
  })
  </code></pre>
  
  <p>With this code i have succeeded to test the <code>open</code>, now i just need to test <code>focus</code>.</p>