简体   繁体   English

在赛普拉斯测试中,我如何存根 function 的参数

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

I am writing a Cypress integration test for a Google Optimize experiment and I would like to stub the experiment variant value provided by gtag library.我正在为 Google Optimize 实验编写 Cypress 集成测试,我想存根gtag库提供的实验变体值

The value is provided as the argument of callback for this function:该值作为此 function 的callback参数提供:

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

How can I stub argument "value"?我怎样才能存根参数“值”? (without stubbing the callback return) (不打断回调返回)

-- --

Docs for:文档:

I don't know much about gtag, but looking at the reference page it may be possible to stub if you are using the "external" function pattern shown on that page rather than the "inline" function you have above.我对 gtag 了解不多,但如果您使用该页面上显示的“外部”function 模式而不是上面的“内联”function 模式,那么查看参考页面可能会存根。

The way to stub internal functions in a React or other framework is to expose it on the window object.在 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
 })

Then in the test, you might set up the stub in the beforeLoad event然后在测试中,您可以在 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)
    })
  },
})

This should instantiate the stub at the earliest point in the page load, provided the reference has been set up.这应该在页面加载的最早点实例化存根,前提是已经设置了引用。

Check the console.logs are firing in the right order, if not then there might be a delay in referencing the function and you can choose the stub point with cy.window() .检查 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