簡體   English   中英

在賽普拉斯測試中,我如何存根 function 的參數

[英]In a Cypress test how can I stub argument of a function

我正在為 Google Optimize 實驗編寫 Cypress 集成測試,我想存根gtag庫提供的實驗變體值

該值作為此 function 的callback參數提供:

gtag('event', 'optimize.callback', {
    name: '<experiment_id_A>',
    callback: (value) => 'unknown',
 });

我怎樣才能存根參數“值”? (不打斷回調返回)

--

文檔:

我對 gtag 了解不多,但如果您使用該頁面上顯示的“外部”function 模式而不是上面的“內聯”function 模式,那么查看參考頁面可能會存根。

在 React 或其他框架中存根內部函數的方法是將其暴露在window object 上。

function implementExperimentA(value) {
  if (value ==  '0') {
    // Provide code for visitors in the original.
  } else if (value == '1') {
    // Provide code for visitors in first variant.
  } else if (value == '2') {
    // Provide code for visitors in section variant.
  }
  ...
}

if (window.Cypress) {
  // Cypress is active
  console.log('referencing "implementExperimentA" on window')
  window.implementExperimentA = implementExperimentA;
}   

gtag('event', 'optimize.callback', {
    name: '<experiment_id_A>',
    callback: implementExperimentA
 })

然后在測試中,您可以在 beforeLoad 事件中設置存根

cy.visit('http://localhost:3000', {
  onBeforeLoad(win) {
    // Stub your functions here
    cy.stub(win, 'implementExperimentA').callsFake((realValue) => {
      const mockValue = 'abc'
      console.log(`implementExperimentA called with ${realValue}, subbing ${mockValue}`)
      return window.implementExperimentA(mockValue)
    })
  },
})

這應該在頁面加載的最早點實例化存根,前提是已經設置了引用。

檢查 console.logs 是否以正確的順序觸發,如果不是,則引用 function 可能會延遲,您可以使用cy.window()選擇存根點。

cy.visit('http://localhost:3000')

...

cy.window().then(win => {
  // Stub your functions here
  cy.stub(win, 'implementExperimentA').callsFake((realValue) => {
    const mockValue = 'abc'
    console.log(`implementExperimentA called with ${realValue}, subbing ${mockValue}`)
    return window.implementExperimentA(mockValue)
  })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM