反应酶测试嵌套组件

时间:2019-06-12 09:07:01

标签: reactjs enzyme

我有两个非常简单的组件嵌套在一起,我正在尝试编写一个测试,我浏览了酶文档并使用了一些示例,但是没有运气...

文章组成部分:

import React, { Component } from 'react';
import styled from 'styled-components';

const Styles = styled.div`
    padding-top: 40px;
    padding-bottom: 40px;
    font-family: Montserrat Alternates;
`
class Article extends Component {
    render() {
        const { title, text } = this.props;
        return (
            <Styles>
                <hr />
                <h1>{ title }</h1>
                <p>{ text }</p>
                <hr />
            </Styles>
        )
    }
}
export default Article;

其中包含“文章”组件的“联系”组件:

import React, { Component } from 'react';
import Article from '../../components/article/Article';

class Contact extends Component {
    render () {
        return (
            <div>
                <Article 
                    title='Contact Us'
                    text='Boy favourable day can introduced sentiments entreaties. Noisier carried of in warrant because. So mr plate seems cause chief widen first. Two differed husbands met screened his. Bed was form wife out ask draw. Wholly coming at we no enable. Offending sir delivered questions now new met. Acceptance she interested new boisterous day discretion celebrated. 
                    Article nor prepare chicken you him now. Shy merits say advice ten before lovers innate add. She cordially behaviour can attempted estimable. Trees delay fancy noise manor do as an small. Felicity now law securing breeding likewise extended and. Roused either who favour why ham. '
                />
            </div>
        );
    }
}

export default Contact;

我的测试:

import React from 'react';
import { shallow, configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Contact from './Contact';
import Article from '../../components/article/Article';

configure({ adapter: new Adapter() });

describe('Does Contact Component Render', () => {
    let contact = shallow(<Contact />);

    it('Contact renders article component', () => {
        console.log(contact.debug());
        expect(contact.find(Article)).toBe(true);
    });
})

控制台错误:

Does Contact Component Render › Contact renders article component

    expect(received).toBe(expected) // Object.is equality

    Expected: true
    Received: {}

      12 |     it('Contact renders article component', () => {
      13 |         console.log(contact.debug());
    > 14 |         expect(contact.find(Article)).toBe(true);
         |                                       ^     });
      })

      at Object.toBe (src/pages/Contact/Contact.test.js:14:39)

我还读到,显然我们不应该测试导入组件的行为,而该行为应该在我所做的组件测试中涵盖。但是,如何测试Article组件是否实际上是Contact组件的一部分??

1 个答案:

答案 0 :(得分:1)

Find返回节点,您正在针对布尔值(true)对其进行测试。如果要测试Article是否存在,只需执行

expect(contact.find(Article)).toHaveLength(1);

相关问题