简体   繁体   中英

mocking a conditional window.open function call with jest

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 windows.open(args) to open it. then to make sure that i focus on it.

Test link validity:

export function isValidURL(url: string): boolean {
  try {
    new URL(url)
    return true
  } catch (e) {
    console.warn(`Invalid URL: ${url}`)
    return false
  }
}

Open link:

export function openURL(url: string): void {
  if (isValidURL(url)) {
    const exTab = window.open(url, "_blank")
    if (exTab) exTab.focus()
  }
}

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.

My issay:

describe("Test tools.openURL()", () => {
  test("it should open link if valid.", () => {
    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
  })
})

With this code i have succeeded to test the open , now i just need to test focus .

'open' is readonly property. Instead of jest.spyOn(window, "open") Try:

Object.defineProperty(window, 'open', { value: <your mock> });

in place of <your mock> locate mock object or object that should be returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM