2017-06-13 275 views
1

以下是我的组件。 mobx状态就在组件的主体中,我没有为它创建一个单独的存储。在Jest单元测试中访问React组件中的mobx observable属性

我的问题是如何在jest /酶单元测试中访问那些mobx状态变量?

import React, { Component } from 'react'; 
import { BookIcon } from 'react-octicons-svg'; 
import { observable } from 'mobx'; 
import { observer } from 'mobx-react'; 


@observer 
class Wallet extends Component { 

    static propTypes = { 
     name: React.PropTypes.string, 
     wallet: React.PropTypes.object.isRequired 
    } 

    @observable showPassbook = false; 
    @observable wallet = Object.assign({}, this.props.wallet); 

    render() { 

     const walletTitle = this.wallet.title || this.wallet.wallet_name || this.props.name || "no name"; 

     return (<div> 
       <h2>Wallet for {walletTitle}</h2> 
       <div className="row"> 
        <div className="col-md"> 
         <ul className="list-unstyled mt-2"> 
          <li><strong>Balance:</strong> {formatNumber(Number(this.wallet.balance.amount), this.wallet.balance.currency)} {this.wallet.balance.currency}</li> 
          <li><strong>State:</strong> {this.wallet.state}</li> 
         </ul> 
        </div>  
       </div> 


       <div> 
        <button className="btn-link" title="Show Passbook" onClick={() => { this.showPassbook = true; }}><BookIcon /> Show Passbook</button> 
        </div> 
       {this.showPassbook && (<div>Passbook</div>)}  
      </div> 
     )} 
}; 

export default Wallet; 

我的玩笑单元测试的相关部分是:

it("button to get passbook", function() { 
    const wrapper = shallow(<Wallet name="carlos" wallet={walletData}/>) 
    console.log("showpassbook", this.showPassbook); 
    }) 

我怎样才能获得mobx我的单元测试中观察到的属性? 当前this.showPassbook或wrapper.showPassbook未定义。

回答

0

你可以包装的instance和访问现场:在我的测试

it("button to get passbook", function() { 
    const wrapper = shallow(<Wallet name="carlos" wallet={walletData}/>) 
    console.log("showpassbook", wrapper.instance().showPassbook); 
}) 
+0

我可以使用wrapper.instance()showPassbook = true来更改组件showPassbook的价值?如果showPassbook为真,则有条件呈现。我想测试一下。 –

+0

@ criver.to我不知道,恐怕。 – Tholle

相关问题