我是反应测试新手 所以,基本上,我有
totalCostakedBtc
和 btcPrice
处于 useState ,初始值为 0。
在 useEffect 中,它是从 API 调用中设置的。
和
这是我的 jsx 文件中
<div className={isConnected ? 'tvl-white' : 'App-tvl'} data-testid="loaded-TVL">
<span>TVL</span>
<span>${formatNumber(totalCostakedBtc * btcPrice)}</span>
</div>
它的 testid 为已加载 TVL TotalCostakedBTC 和 btcPrice 是从 useEffect 获取的 那么,如何处理这种类型的测试用例,我想检查它是否大于0。
const tvlElement = await waitFor(() => getByTestId('loaded-TVL'), { timeout: 3000 })
screen.debug()
const tvlText = tvlElement.textContent
// Define a regular expression to match the value after $
const regex = /\$(\d+(\.\d+)?)/
const match = tvlText.match(regex)
// Ensure that the match is found and the value is not empty
expect(match).toBeTruthy()
expect(match[1]).toBeTruthy() // match[1] contains the captured value
// You can further assert the format or specific value if needed
// For example, to check if the value is a valid number:
const valueAfterDollar = parseFloat(match[1])
expect(valueAfterDollar).not.toBeNaN()
expect(valueAfterDollar).toBeGreaterThan(0)
上面的代码是GPT3.5编写的
但这失败了,因为它给了我 0,因为我最初使用 useState 将其设置为 0。 谁能帮我做这个测试。
const [btcPrice, setBtcPrice] = useState(0)
useEffect(() => {
fetchBtcPrice()
.then(data => {
setBtcPrice(data)
})
.catch(error => console.log('failed to fetch BTC price', error))
getTotalCostakedBtc()
}, [])
并且 fetchBtcPrice 位于 ./Api.js 中
export const fetchBtcPrice = async () => {
try {
const response = await fetch(cryptocompareUrl)
const data = await response.json()
return `${data.USD}`
} catch (error) {
return error
}
}
这就是 btcPrice 的设置方式。同样设置了totalcostakedBtc。
所以,我有 2 个调用 api 的方法。 所以,在测试中嘲笑他们
jest.mock('../../helper/Api', () => ({
fetchBtcPrice: jest.fn().mockResolvedValue('10'),
getTotalCostakedBtc: jest.fn().mockResolvedValue([5, true]), // Assuming you want to simulate 'true' for show notification
}))
并检查期望值
await act(async () => {
const tvlElement = await waitFor(() => screen.getByTestId('loaded-TVL'), { timeout: 3000 })
// screen.debug()
const tvlText = tvlElement.textContent
const expectedTotalValue = 5 * 10
expect(tvlText).toEqual(`TVL$${expectedTotalValue}`)
})
解决了我的疑问。