/ / Testowanie React componentWillUnmount using Jest - reactjs, jestjs

Testowanie React componentWillUnmount using Jest - reactjs, jestjs

Używam React TestUtil.renderIntoDocument przetestować klasę komponentów React, lubię to (tylko ja używam TypeScript zamiast Babel):

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

To działa, ale chcę napisać test, który to weryfikuje componentWillUnmount zachowuje się zgodnie z oczekiwaniami. Wydaje się jednak, że biegacz testowy nigdy nie odmontowuje komponentu, co nie jest zaskakujące. Moje pytanie brzmi: jak mogę odmontować komponent z testu? The TestUtil nie ma niczego, co wygląda tak, jak chcę, coś podobnego do tego removeFromDocument Mogę sobie wyobrazić.

Odpowiedzi:

4 dla odpowiedzi № 1

Zgadza się, ale TestUtils.renderIntoDocument zwraca wartość ReactComponent z dostępem do metod cyklu życia komponentu.

Możesz więc zadzwonić ręcznie component.componentWillUnmount().


9 dla odpowiedzi nr 2

Za pomocą enzyme 3 biblioteki shallow() i unmount(), możesz sprawdzić, czy metody cyklu życia zostały nazwane tak:

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 dla odpowiedzi nr 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 dla odpowiedzi nr 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

Kod

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