javascript - 在 Jest 单元测试中访问 React 组件中的 mobx 可观察属性

标签 javascript reactjs jestjs mobx

下面是我的组件。 mobx 状态仅在组件主体中,我没有为其创建单独的存储。

我的问题是如何在 jest/enzyme 单元测试中访问这些 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;

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

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

如何在单元测试中访问 mobx 可观察属性? 目前 this.showPassbook 或wrapper.showPassbook 未定义。

最佳答案

您可以获得instance包装器并访问该字段:

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

关于javascript - 在 Jest 单元测试中访问 React 组件中的 mobx 可观察属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44528834/

相关文章:

添加空白函数时javascript函数错误

javascript - 使用 onClick 从数组中删除元素并使用react

reactjs - 如何使用react-router进行页面滑动(更改)

javascript - 正确的 React 方式来处理父组件中仅作用于选定子组件的函数?

typescript - 在 Jest TypeScript 中找不到名称 'it'

javascript - 如何更有效地从 CodeSignal 获得 arrayMaxConsecutiveSum?

javascript - 基于对象内部数组的新对象数组?

javascript - 如何在 Jest 测试中模拟影子元素

javascript - 如何在 jest/enzyme 测试中测试 axios get 请求函数?

Twig 模板内容的 Javascript 正则表达式