[英]How to Stub a module in 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 調用仍在發生。 文檔本身讓我推斷我應該這樣寫,但它不起作用。
您可以在 window 上公開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);
})
或者使用攔截來存根 API 調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.