2017-10-18 118 views
0

组件的测试,我有这样的组件:阵营与酶

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; 

我怎样写元件测试使用酶对此做出何种反应成分?我是新来的反应和酶。任何帮助都会非常可观。

回答

1

这可能是一个测试用摩卡:

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

太谢谢你了。它非常帮助我...... – Khushi

+0

酷!乐意效劳 – lipp

0

下面是使用酶+玩笑耍赖采取测试DOM的example(从笑话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'); 
}); 

我建议你去,虽然我给的链接 - 它包含了测试的很好的例子发生反应,用玩笑成分+酶。