2017-10-18 10 views
0

J'ai un composant comme ceci:React test de composants avec l'enzyme

component.js

import React from "react"; 
import PropTypes from "prop-types"; 

const Test = ({ text }) => (
<div> 
    {text.split("\n").map((item, key) => { 
    return (
    <span key={key}> 
     {item} 
     <br /> 
    </span> 
    ); 
    })} 
    </div> 
); 

Test.propTypes = { 
text: PropTypes.string.isRequired 
}; 

export default Test; 

Comment puis-je écrire essai pour ce composant réagir en utilisant l'enzyme? Je suis nouveau pour réagir et enzyme. Toute aide sera vraiment appréciable.

Répondre

1

Cela pourrait être un test à l'aide mocha:

import {shallow} from 'enzyme' 
import assert from 'assert' 
import Test from './Test' 

describe('component Test',() => { 
    it('should show a span for each line of "text" prop',() => { 
    const text = `foo 
    bar 
    ` 
    const wrapper = shallow(<Test text={text} />) 
    const spans = wrapper.find('span') 
    assert.equal(spans.length, 2) 
    assert.equal(spans.at(0).text(), 'foo') 
    assert.equal(spans.at(1).text(). 'bar') 
    }) 

    it('should throw if "text" prop is not provided',() => { 
    assert.throws(() => { 
     shallow(<Text />) 
    }) 
    }) 
}) 
+0

Merci beaucoup. Cela m'aide beaucoup ... – Khushi

+0

cool! heureux de vous aider – lipp

0

Voici sans vergogne prise example dom test utilisant une enzyme + plaisanterie (de plaisanterie web site):

// __tests__/CheckboxWithLabel-test.js 

import React from 'react'; 
import {shallow} from 'enzyme'; 
import CheckboxWithLabel from '../CheckboxWithLabel'; 

test('CheckboxWithLabel changes the text after click',() => { 
    // Render a checkbox with label in the document 
    const checkbox = shallow(
    <CheckboxWithLabel labelOn="On" labelOff="Off" /> 
); 

    expect(checkbox.text()).toEqual('Off'); 

    checkbox.find('input').simulate('change'); 

    expect(checkbox.text()).toEqual('On'); 
}); 

je vous recommande d'aller si le lien que j'ai donné - il contient de beaux exemples de tests réagissent composants à l'aide Jest + Enzyme.