2017-04-09 105 views
0

我想測試我的NavLink有一定網址:如何與摩卡測試`NavLink`從反應路由器-DOM

Splash.js

import React from 'react'; 
import { NavLink } from 'react-router-dom' 
import Logo from '../shared/logo/index'; 
import * as styles from './style.css'; 

class Splash extends React.Component { 
    render(){ 
    return (
     <div className={styles.indexAppContent}> 
     <NavLink to="/home" className={styles.index}> 
      <Logo /> 
     </NavLink> 
     </div> 
    ); 
    } 
} 

export default Splash; 

測試

/* eslint-disable object-property-newline */ 
import React from 'react'; 
import ReactTestUtils from 'react-dom/test-utils' 
import { expect } from 'chai'; 
import { NavLink } from 'react-router-dom' 
import { shallow } from 'enzyme'; 


describe('<Splash />',() => { 

    it('Logo links to home',() => { 
    expect(wrapperNavLink.prop('to')) 
     .equals('/home'); 
    }) 

}); 

我該如何測試呈現的href值的反應?

回答

2

有兩種方法可以測試傳遞道具是否正確地到達組件。在隔離

1.Test組件 -

import React from 'react'; 
import { expect } from 'chai'; 
import { shallow, mount, render } from 'enzyme'; 
import { NavLink } from 'react-router-dom'; 

describe("<NavLink />",() => { 
    it("1.contains correct passed prop",() => { 
     const comp = (
      <NavLink to="/home" className={"test"}> 
       NaveLink Test 
      </NavLink> 
     ); 
     const wrapper = shallow(comp); 
     expect(wrapper.instance().props.to).to.equal("/home"); 
    }); 
}); 

在你的情況下整個e.g組件<Splash /> 2.測試組件。

import React from 'react'; 
import { expect } from 'chai'; 
import { shallow, mount, render } from 'enzyme'; 
import { NavLink } from 'react-router-dom'; 
import Splash from './splash'; // <----------- import the component you want to test 

describe("<Splash />",() => { 
    it("2.contains correct passed prop",() => { 
     const comp = (
      <Splash /> 
     ); 
     const wrapper = shallow(comp); 

     expect(wrapper.find(NavLink).first().props().to).to.equal("/home"); 
    }); 
}); 
+0

感謝隊友,花了我一段時間回來這:)有趣的話。 'wrapper.find(NavLink).first()。props()。to',所以你通過傳遞實際的'component'來使用find。有沒有關於我錯過的明確文件? –

+0

@JamieHutber您的歡迎。我想你可以查看airbnb酶文檔, – WitVault