2015-03-15 2 views
1

Есть ли способ вызвать событие error тега img для проверки моего обратного вызова onError? Например, учитывая этот компонент,React + Jest - тестирование события `error` на IMG-тегах

import React from 'react'; 

/** 
* Self removing <img> when the `src` or image 
* does not load or is unavailable. 
* 
* Usage: (tip: it's how you use the <img> tag, basically) 
* <Img src={} alt={} ../..> 
*/ 
var Img = React.createClass({ 
    /** 
    * Force update so `refs` will be available 
    */ 
    componentDidMount() { 
    this.forceUpdate(); 
    }, 

    render() { 
    // Omit any passed `onError` prop so that 
    // it is never overridden by mistake 
    var { onError, ...other } = this.props; 

    return (
     <span ref="container"> 
     <img {...other} onError={this._handleError} /> 
     </span> 
    ) 
    }, 

    /** 
    * Remove itself when image is not found 
    */ 
    _handleError() { 
    this.refs.container.getDOMNode().remove(); 
    } 
}); 

export default Img; 

и этот набор тестов:

it('should remove itself when an error occurs while loading the image', function() { 
    // rendered = TestUtils.renderIntoDocument(<Img />); 
}); 

ответ

3

я нашел Реагировать протестируем утилиты (React.addons.TestUtils), чтобы быть очень полезным, предоставляя утилиты как Simulate (React.addons.TestUtils.Simulate). В этом случае Simulate выполнит трюк.

Исходя из React's Documentation на Test Utilities:

Имитировать отправку событий на узле DOM с дополнительными данными о событиях данныеСобытия. Это, возможно, самая полезная утилита в ReactTestUtils.

it('should remove itself when an error occurs while loading the image', function() { 
    var rendered = TestUtils.renderIntoDocument(<Img />); 
    var img = TestUtils.findRenderedDOMComponentWithTag(rendered, 'img'); 
    TestUtils.Simulate.error(img); 

    // In this case, we can try to find (again) the tag. 
    // `TestUtils.findRenderedDOMComponentWithTag` throws an error 
    // when the provided tag cannot be found. 
expect(function() { 
    TestUtils.findRenderedDOMComponentWithTag(rendered, 'img'); 
}).toThrow(); 
}); 

Ниже можно попытаться быть не по теме, хотя. Примерный компонент можно было бы улучшить, используя вместо этого state.

import React from 'react'; 

/** 
* Self removing <img> when the `src` or image 
* does not load or is unavailable. 
* 
* Usage: (tip: it's how you use the <img> tag, basically) 
* <Img src={} alt={} ../..> 
*/ 
var Img = React.createClass({ 
    // We'll set `error` to false to load and display the image, 
    // only will it be true when an error occurs 
    getInitialState() { 
    return { error: false } 
    }, 

    render() { 
    // Omit any passed `onError` prop so that 
    // it is never overridden by mistake 
    var { onError, ...other } = this.props; 

    return !this.state.error ? (
     <span> 
     <img {...other} onError={this._handleError} /> 
     </span> 
    ) : null; 
    }, 

    /** 
    * Set `state` error to true to remove the 
    * the dom nodes themselves 
    */ 
    _handleError() { 
    this.setState({ error: true }); 
    } 
}); 

export default Img; 

А затем со следующими тестами:

it('should remove itself when an the image loads with an error', function() { 
    var rendered = TestUtils.renderIntoDocument(<Img />); 
    var img = TestUtils.findRenderedDOMComponentWithTag(rendered, 'img'); 
    TestUtils.Simulate.error(img); 

    // When no results come out of `findRenderedDOMComponentWithTag`, 
    // it throws an error 'Did not find exactly one match for tag:img' 
    expect(function() { 
    TestUtils.findRenderedDOMComponentWithTag(rendered, 'img') 
    }).toThrow('Did not find exactly one match for tag:img'); 
    expect(rendered.state.error).toBe(true); 
}); 
Смежные вопросы