2016-07-26 38 views
15

我正在使用Enzyme爲React寫測試。反應酶測試,無法讀取屬性'有'未定義

我的測試是非常簡單的:

import OffCanvasMenu from '../index'; 
import { Link } from 'react-router'; 

import expect from 'expect'; 
import { shallow, mount } from 'enzyme'; 
import sinon from 'sinon'; 
import React from 'react'; 

describe('<OffCanvasMenu />',() => { 
    it('contains 5 <Link /> components',() => { 
    const wrapper = shallow(<OffCanvasMenu />); 
    expect(wrapper.find(<Link />)).to.have.length(5); 
    }); 
}); 

此代碼基本上是直接取自airbnb/enzyme docs,但返回錯誤:對我在做什麼

FAILED TESTS: 
    <OffCanvasMenu /> 
    ✖ contains 5 <Link /> components 
     Chrome 52.0.2743 (Mac OS X 10.11.6) 
    TypeError: Cannot read property 'have' of undefined 

我有點不清楚與文檔不同。任何指導極大的讚賞。

回答

10

使用Link,而不是<Link />

describe('<OffCanvasMenu />',() => { 
    it('contains 5 <Link /> components',() => { 
    const wrapper = shallow(<OffCanvasMenu />); 
    expect(wrapper.find(Link)).to.have.length(5); 
    }); 
}); 

它出現在第一個例子中的Airbnb /酶文檔:

it('should render three <Foo /> components',() => { 
    const wrapper = shallow(<MyComponent />); 
    expect(wrapper.find(Foo)).to.have.length(3); 
    }); 
+0

感謝您的迴應 - 我看到與'鏈接'相同的錯誤。我正在關注文檔,儘管我使用的代碼導入了邁克爾傑克遜的「期望」,我不確定是否會拋出它(我也檢查過文檔)。 – Toby

+0

你使用了什麼斷言庫? 試試這個 - 'console.log('length',wrapper.find(Link).length);',看看控制檯中出現了什麼。 –

+0

添加它會在日誌中產生預期的條目 - 「5」。我和Chai一起使用Karma,但與Michael Jackson的[期望](https://github.com/mjackson/expect)一起使用。 – Toby

4

在他們的文件酶是用柴斷言,所以如果你想要使用expect(***).to.have.length(***),您需要安裝chai-enzyme並使用其expect。因此,如果您使用Jest快照,它將導致expect(***).toMatchSnapshot()的問題,但是這個article將幫助您解決它,因此您可以同時執行這兩個操作。

+0

謝謝 - 這對我們不識別所有不同庫的語法的新手們很有幫助! –

相關問題