javascript - test - tomatchsnapshot enzyme
Pruebas unitarias Reactuar clic fuera del componente (2)
Use sinon para rastrear el handleClickOutside se llama o no. Por cierto, acabo de lanzar nuestro proyecto donde necesito esta prueba de unidad en el componente Nav . De hecho, cuando haces clic en el exterior, todos los submenús deberían estar cerrados.
import sinon from ''sinon'';
import Component from ''../src/Component'';
it(''handle clicking outside'', () => {
const handleClickOutside = sinon.spy(Component.prototype, ''handleClickOutside'');
const wrapper = mount(
<div>
<Component {... props} />
<div><a class="any-element-outside">Anylink</a></div>
</div>
);
wrapper.find(''.any-element-outside'').last().simulate(''click'');
expect(handleClickOutside.called).toBeTruthy();
handleClickOutside.restore();
})
Usando el código de esta respuesta para resolver haciendo clic fuera de un componente:
componentDidMount() {
document.addEventListener(''mousedown'', this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener(''mousedown'', this.handleClickOutside);
}
setWrapperRef(node) {
this.wrapperRef = node;
}
handleClickOutside(event) {
if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
this.props.actions.something() // Eg. closes modal
}
}
No puedo averiguar cómo probar en unidad el camino infeliz para que la alerta no se ejecute, lo que tengo hasta ahora:
it(''Handles click outside of component'', () => {
props = {
actions: {
something: jest.fn(),
}
}
const wrapper = mount(
<Component {... props} />,
)
expect(props.actions.something.mock.calls.length).toBe(0)
// Happy path should trigger mock
wrapper.instance().handleClick({
target: ''outside'',
})
expect(props.actions.something.mock.calls.length).toBe(1) //true
// Unhappy path should not trigger mock here ???
expect(props.actions.something.mock.calls.length).toBe(1)
})
He intentado:
- enviando a través de
wrapper.html() -
.finda un nodo y enviándolo (no se burla de unevent.target) -
.simulateclicken un elemento dentro (no.simulatedetector de eventos)
Estoy seguro de que me estoy perdiendo algo pequeño, pero no pude encontrar un ejemplo de esto en ninguna parte.
import { mount } from ''enzyme''
import React from ''react''
import ReactDOM from ''react-dom''
it(''Should not call action on click inside the component'', () => {
const map = {}
document.addEventListener = jest.fn((event, cb) => {
map[event] = cb
})
const props = {
actions: {
something: jest.fn(),
}
}
const wrapper = mount(<Component {... props} />)
map.mousedown({
target: ReactDOM.findDOMNode(wrapper.instance()),
})
expect(props.actions.something).not.toHaveBeenCalled()
})
La solución de this problema enzimático en github.