如何在 Cypress 中存根模块

时间:2021-05-10 16:35:53

标签: javascript reactjs cypress

我正在尝试使用 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 调用仍在发生。文档本身让我推断我应该这样写,但它不起作用。

1 个答案:

答案 0 :(得分:4)

你可以在窗口上暴露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 调用。