mardi 1 octobre 2019

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 and maybe to fake it's logiaue 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 urlError: string = "htts//url2.de9v"
    const urlSuccess: string = "https://www.url1.dev"

    const dontOpenMocking = jest.spyOn(window, "open").mockImplementation()
    const openMocking = jest.spyOn(window, "open").mockImplementation()

    expect(dontOpenMocking).toHaveBeenCalledTimes(0)
    expect(openMocking).toHaveBeenCalled()
  })
})

Aucun commentaire:

Enregistrer un commentaire