2016-04-22 19 views
7

Sommario:jsdom: dispatchEvent/addEventListener non sembra funzionare

Sto tentando di testare un componente che ascolta eventi DOM nativi nella sua componentWillMount reagire.

Sto trovando che jsdom (@8.4.0) non funziona come previsto quando si tratta di inviare eventi e aggiungere listener di eventi.

Il bit più semplice di codice posso estrarre:

window.addEventListener('click',() => { 
    throw new Error("success") 
}) 

const event = new Event('click') 
document.dispatchEvent(event) 

throw new Error('failure') 

Questo getta "fallimento".


Contesto:

A rischio di cui sopra essendo un XY problem, voglio fornire più contesto.

Ecco una versione estratta/semplificata del componente che sto provando a testare. You can see it working on Webpackbin.

import React from 'react' 

export default class Example extends React.Component { 
    constructor() { 
    super() 
    this._onDocumentClick = this._onDocumentClick.bind(this) 
    } 

    componentWillMount() { 
    this.setState({ clicked: false }) 
    window.addEventListener('click', this._onDocumentClick) 
    } 

    _onDocumentClick() { 
    const clicked = this.state.clicked || false 
    this.setState({ clicked: !clicked }) 
    } 


    render() { 
    return <p>{JSON.stringify(this.state.clicked)}</p> 
    } 
} 

Ecco la prova che sto cercando di scrivere.

import React from 'react' 
import ReactDOM from 'react-dom' 
import { mount } from 'enzyme' 

import Example from '../src/example' 

describe('test',() => { 
    it('test',() => { 
    const wrapper = mount(<Example />) 

    const event = new Event('click') 
    document.dispatchEvent(event) 

    // at this point, I expect the component to re-render, 
    // with updated state. 

    expect(wrapper.text()).to.match(/true/) 
    }) 
}) 

Solo per completezza, ecco la mia test_helper.js che inizializza jsdom:

import { jsdom } from 'jsdom' 
import chai from 'chai' 

const doc = jsdom('<!doctype html><html><body></body></html>') 
const win = doc.defaultView 

global.document = doc 
global.window = win 

Object.keys(window).forEach((key) => { 
    if (!(key in global)) { 
    global[key] = window[key] 
    } 
}) 

caso Riproduzione:

Ho un caso Repro qui: https://github.com/jbinto/repro-jsdom-events-not-firing

git clone https://github.com/jbinto/repro-jsdom-events-not-firing.git cd repro-jsdom-events-not-firing npm install npm test

risposta

3

Il problema qui è che il jsdom fornito document non è in realtà sempre utilizzato da test enzimatici.

Enzyme utilizza renderIntoDocument da React.TestUtils.

https://github.com/facebook/react/blob/510155e027d56ce3cf5c890c9939d894528cf007/src/test/ReactTestUtils.js#L85

{ 
    renderIntoDocument: function(instance) { 
    var div = document.createElement('div'); 
    // None of our tests actually require attaching the container to the 
    // DOM, and doing so creates a mess that we rely on test isolation to 
    // clean up, so we're going to stop honoring the name of this method 
    // (and probably rename it eventually) if no problems arise. 
    // document.documentElement.appendChild(div); 
    return ReactDOM.render(instance, div); 
    }, 
// ... 
} 

Questo significa tutti i nostri test enzima non vengono eseguiti contro la jsdom fornito document, ma piuttosto in un nodo div indipendente da qualsiasi documento.

Enzyme utilizza solo il document fornito da jsdom per i metodi statici, ad es. getElementById ecc. Non è utilizzato per memorizzare/utilizzare elementi DOM.

Per eseguire questo tipo di test, ho fatto ricorso a chiamare effettivamente ReactDOM.render e ad asserire sull'output utilizzando i metodi DOM.

6

Stai trasmettendo l'evento a document così window non lo vedrà perché per impostazione predefinita non verrà visualizzato. È necessario creare l'evento con bubbles impostato su true. Esempio:

var jsdom = require("jsdom"); 

var document = jsdom.jsdom(""); 
var window = document.defaultView; 

window.addEventListener('click', function (ev) { 
    console.log('window click', ev.target.constructor.name, 
       ev.currentTarget.constructor.name); 
}); 

document.addEventListener('click', function (ev) { 
    console.log('document click', ev.target.constructor.name, 
       ev.currentTarget.constructor.name); 
}); 

console.log("not bubbling"); 

var event = new window.Event("click"); 
document.dispatchEvent(event); 

console.log("bubbling"); 

event = new window.Event("click", {bubbles: true}); 
document.dispatchEvent(event); 
+1

'nuova window.event ("click");' ermagerd. 'doc.createEvent ('MouseEvents'). initEvent ('click', true, true)' restituisce undefined in jsdom ... 1.5hrs per trovare la risposta O.o – Larry

0

Codice: https://github.com/LVCarnevalli/create-react-app/blob/master/src/components/datepicker

Link: ReactTestUtils.Simulate can't trigger event bind by addEventListener?

Componente:

componentDidMount() { 
ReactDOM.findDOMNode(this.datePicker.refs.input).addEventListener("change", (event) => { 
    const value = event.target.value; 
    this.handleChange(Moment(value).toISOString(), value); 
    }); 
} 

prova:

it('change empty value date picker',() => { 
    const app = ReactTestUtils.renderIntoDocument(<Datepicker />); 
    const datePicker = ReactDOM.findDOMNode(app.datePicker.refs.input); 
    const value = ""; 

    const event = new Event("change"); 
    datePicker.value = value; 
    datePicker.dispatchEvent(event); 

    expect(app.state.formattedValue).toEqual(value); 
}); 
Problemi correlati