/ / परीक्षण रिएक्ट घटकWillUnmount Jest का उपयोग करते हुए - reactjs, jestjs

जेस्ट का उपयोग कर प्रतिक्रिया घटक का परीक्षण करें - प्रतिक्रिया, jestjs

मैं रिएक्ट का उपयोग कर रहा हूं TestUtil.renderIntoDocument एक प्रतिक्रिया घटक वर्ग का परीक्षण करने के लिए, इस तरह (केवल मैं Babel के बजाय टाइपस्क्रिप्ट का उपयोग कर रहा हूं):

describe("MyComponent", () => {
it("will test something after being mounted", () => {
var component = TestUtils.renderIntoDocument(<MyComponent />);
// some test...
})
})

यह काम करता है, लेकिन मैं एक परीक्षण लिखना चाहता हूं जो इसे सत्यापित करता है componentWillUnmount अपेक्षा के अनुरूप व्यवहार करता है। हालांकि, ऐसा लगता है कि परीक्षण धावक घटक को कभी भी अस्वीकार नहीं करता है, जो आश्चर्य की बात नहीं है। तो मेरा सवाल है: मैं एक परीक्षण के भीतर से घटक को कैसे अनमाउंट करूं? TestUtil doesn "टी कुछ भी है कि जैसा मैं चाहता हूँ लग रहा है, की तर्ज पर कुछ है removeFromDocument मैं कल्पना करुगा।

उत्तर:

उत्तर № 1 के लिए 4

यह सही है लेकिन TestUtils.renderIntoDocument घटक के जीवनचक्र विधियों तक पहुंच के साथ एक ReactComponent देता है।

तो आप मैन्युअल रूप से कॉल कर सकते हैं component.componentWillUnmount().


जवाब के लिए 9 № 2

का उपयोग करते हुए enzyme 3 पुस्तकालय "रों shallow() तथा unmount(), आप परीक्षण कर सकते हैं यदि जीवनचक्र विधियों को इस तरह कहा गया है:

it(`lifecycle method should have been called`, () => {
const componentDidMount = jest.fn()
const componentWillUnmount = jest.fn()

// 1. First extends your class to mock lifecycle methods
class Foo extends MyComponent {
constructor(props) {
super(props)
this.componentDidMount = componentDidMount
this.componentWillUnmount = componentWillUnmount
}

render() {
return (<MyComponent />)
}
}

// 2. shallow-render and test componentDidMount
const wrapper = shallow(<Foo />)

expect(componentDidMount.mock.calls.length).toBe(1)
expect(componentWillUnmount.mock.calls.length).toBe(0)

// 3. unmount and test componentWillUnmount
wrapper.unmount()

expect(componentDidMount.mock.calls.length).toBe(1)
expect(componentWillUnmount.mock.calls.length).toBe(1)
})

जवाब के लिए 2 № 3
import { mount } from "enzyme";
import ReactDOM from "react-dom";
...

let container;
beforeEach(() => {
container = document.createElement("div");
mount(<YourReactComponent />, {attachTo: container});
});

afterEach(() => {
ReactDOM.unmountComponentAtNode(container);
});

उत्तर के लिए 1 № 4
Step1: Use "jest.spyOn" on "componentWillUnmount" method.
Step2: Trigger unmount on the mounted component.
Finally: check if componentWillUnmount is called when component is unmounted

कोड

it("componentWillUnmount should be called on unmount", () => {
const component = createComponent();
const componentWillUnmount = jest.spyOn(component.instance(), "componentWillUnmount");
component.unmount();
expect(componentWillUnmount).toHaveBeenCalled();
});