मैं अनुसरण कर रहा हूँ एक ट्यूटोरियल। अतुल्यकालिक क्रियाओं का परीक्षण करने का तरीका दिखाने के लिए ट्यूटोरियल में इस तरह का एक सरल घटक है:
import React from 'react'
const TestAsync = () => {
const [counter, setCounter] = React.useState(0)
const delayCount = () => (
setTimeout(() => {
setCounter(counter + 1)
}, 500)
)
return (
<>
<h1 data-testid="counter">{ counter }</h1>
<button data-testid="button-up" onClick={delayCount}> Up</button>
<button data-testid="button-down" onClick={() => setCounter(counter - 1)}>Down</button>
</>
)
}
export default TestAsync
और परीक्षण फ़ाइल इस तरह है:
import React from 'react';
import { render, cleanup, fireEvent, waitForElement } from '@testing-library/react';
import TestAsync from './TestAsync'
afterEach(cleanup);
it('increments counter after 0.5s', async () => {
const { getByTestId, getByText } = render(<TestAsync />);
fireEvent.click(getByTestId('button-up'))
const counter = await waitForElement(() => getByText('1'))
expect(counter).toHaveTextContent('1')
});
टर्मिनल का कहना है कि waitForElement
को हटा दिया गया है और इसके बजाय waitFor
का उपयोग करना है।
मैं इस परीक्षण फ़ाइल में waitFor
का उपयोग कैसे कर सकता हूं?
8
lomine
14 जिंदा 2021, 22:20
1 उत्तर
सबसे बढ़िया उत्तर
अगर आप उपस्थिति की प्रतीक्षा कर रहे हैं, तो आप इसे इस तरह उपयोग कर सकते हैं:
it('increments counter after 0.5s', async() => {
const { getByTestId, getByText } = render(<TestAsync />);
fireEvent.click(getByTestId('button-up'));
await waitFor(() => {
expect(getByText('1')).toBeInTheDocument();
});
});
जब आप उस तत्व को पकड़ने के लिए getByText('1')
का उपयोग करते हैं तो .toHaveTextContent('1')
की जांच करना थोड़ा "अजीब" होता है, इसलिए मैंने इसे .toBeInTheDocument()
से बदल दिया।
10
Zsolt Meszaros
14 जिंदा 2021, 22:33
act
फ़ंक्शन का उपयोग करके अभिकथन को लपेटना भी संभव होगा? दस्तावेज़ों के आधार पर मुझे समझ में नहीं आता कि किस मामले मेंact
का उपयोग करना है और किस मामले मेंwaitFor
का उपयोग करना है।