【问题标题】:How to Stub a module in Cypress如何在赛普拉斯中存根模块
【发布时间】:2021-05-10 16:35:53
【问题描述】:

我正在尝试使用 Cypress 对模块进行存根。这是我迄今为止尝试过的方法,但没有奏效。

这是我的组件/页面的简短版本

// SomeComponent.jsx

import { useSomething } from './useSomething'

const SomeComponent = () => {
  // useSomething is a custom hook
  const { data, error } = useSomething()

  const renderData = () => {
    // map the data into an array of JSX elements
    return data.map(...)
  }

  return (
    <div>
      {renderData()}
    </div>
  )
}

export default SomeComponent

这是我的自定义钩子的样子

// useSomething.js

import { useState } from 'react'
import { getData } from './db'

export const useSomething = () => {
  const [data, setData] = useState({})
  const [error, setError] = useState()

  useEffect(() => {
    getData().then(data => {
      setData(data)
    }).catch(err => {
      setError(error)
    })

    // ... some other unrelated code here
  }, [])

  return { data, error }
}

getData 是这样的

// getData.js

export const getData = () => {
  const data = // some API call from external services

  return data
}

方法通过db.js(实际上是db/index.js)暴露出来

// db.js

export * from './getData'

我正在尝试对 getData.js 进行存根,以使 e2e 测试更加一致。这就是我所做的。

// something.spec.js

// I'm writing @src just to keep the code sample here short, it's the same file as the db.js I write above
import * as db from '@src/db'

...

// this is how I try to do the stubbing
cy.stub(db, 'getData').resolves(something)

...

上面的存根不起作用。运行测试时,对外部服务的 API 调用仍在发生。文档本身让我推断我应该这样写,但它不起作用。

【问题讨论】:

    标签: javascript reactjs cypress


    【解决方案1】:

    你可以在窗口上暴露db

    // useSomething.js
    
    import { useState } from 'react'
    import * as db from './db'
    
    const { getData } = db;
    
    if (window.Cypress) {     // only when testing
      window.db = db;
    }
    

    在测试中

    cy.window().then(win => {
      cy.stub(win.db, 'getData').resolves(something);
    })
    

    或使用intercept 存根 API 调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      相关资源
      最近更新 更多