2017-08-04 60 views
0

我正在寫一個簡單的測試反應組件使用酶來創建一個淺的克隆,這是不應該的時候失敗。我想看到的兩件事是,如果它變好,並且它有一個道具。這兩個都失敗了。在這裏,我測試的組件和我的規格:使用酶的簡單茉莉花測試失敗。

我的組件:

import * as React from 'react'; 

export default class PortfolioItem extends React.Component<any, any> { 
    render() { 
    // Deconstructing the items obj into these consts 
    const { 
     ID, 
     abbreviation, 
     active, 
     managementCompany, 
     name, 
     targetOperatingReserve 
    } = this.props.item; 
    return (
     <tr className='.item'> 
     <td className='id' >{ID}</td> 
     <td className='abv' >{abbreviation}</td> 
     <td className='active' >{active}</td> 
     <td className='manComp' >{managementCompany}</td> 
     <td className='name' >{name}</td> 
     <td className='tor' >{targetOperatingReserve}</td> 
     </tr> 
    ); 
    } 
} 

我的規格:

import * as React from 'react'; 
import { shallow } from 'enzyme'; 
import PortfolioItem from '../../src/js/components/PortfolioItem'; 

const createShallowPortfolioItem =() => { 
    const props = { 
    item: { 
     ID: 1234567, 
     abbreviation: 'rit', 
     active: true, 
     managementCompany: false, 
     name: 'Jorge Joestar', 
     targetOperatingReserve: 0.0 
    } 
    }; 
    return shallow(<PortfolioItem {...props} />); 
}; 

describe('PortfolioItem',() => { 
    it('it contains the class name item',() => { 
    const portItem = createShallowPortfolioItem(); 
    expect(portItem.is('.item')).toBeTruthy(); 
    }); 

    it('renders the item name',() => { 
    const item = createShallowPortfolioItem(); 
    expect(item.find('.name').text()).toEqual('Jorge Joestar'); 
    }); 
}); 

回答

1

「項」級是在tr,您的組件第一批孩子不上組件本身。在渲染PortfolioItem時,您首先會有一個div,並在div中包含您在渲染中定義的子項。這就解釋了爲什麼第一次測試失敗。 第二次測試失敗,因爲shallow不會創建整個組件,因此沒有子組件,因此沒有類爲「.name」的元素。

因此,您可以使用mount來爲子組件提供完整的渲染。或測試別的東西像

expect(portItem).toEqual(jasmine.anything()) 

不是很花哨,但如果錯誤防止您呈現元件進行檢查將失敗。