【问题标题】:mocking a conditional window.open function call with jest用玩笑模拟条件 window.open 函数调用
【发布时间】:2020-01-31 01:04:08
【问题描述】:

我正在尝试编写一个测试,以确保当我将有效的 URL arg 传递给函数时,它会运行 windows.open(args) 来打开它。然后确保我专注于它。

测试链接有效性:

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

打开链接:

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

我认为我应该模拟一些函数或者伪造它的代码,然后等待它的调用次数或类似的东西。但我是开玩笑和测试的新手,我对如何做到这一点感到非常困惑。

我的观点:

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

使用这段代码我已经成功测试了open,现在我只需要测试focus

【问题讨论】:

  • window.open('htts//url2.de9v') 不会出错
  • @r3wt 我根据另一个想法(解决方法)编辑了我的文章,现在我成功测试了open。我仍然需要测试focus 以获得 100% 的覆盖率。请看一下..

标签: javascript typescript testing mocking jestjs


【解决方案1】:

'open' 是只读属性。 而不是jest.spyOn(window, "open")试试:

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

代替&lt;your mock&gt;定位应该返回的模拟对象或对象。

【讨论】:

  • 对不起,我不明白!请问你能给我更多的提示吗?
  • @MalekBoubakri 我已经更新了答案。而不是 放置对象(或模拟),该 window.open 应该返回
  • 我根据另一个想法(一种解决方法)编辑了我的文章,现在我成功测试了open。我仍然需要测试focus 以获得 100% 的覆盖率。请看一下..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 2019-10-01
  • 2022-01-26
  • 2023-03-17
  • 1970-01-01
  • 2017-01-30
相关资源
最近更新 更多