簡體   English   中英

如何在反應中訪問摩卡測試中的道具

[英]how to access props in mocha test in react

我正在嘗試在我當前的測試用例中訪問道具,但是一旦我從包裝器 class 中獲得一個實例,道具就會得到 null ,它沒有通過測試用例

我嘗試了 props() 方法來訪問道具,但到目前為止還沒有運氣。 有沒有其他方法可以訪問道具並在摩卡咖啡中進行測試?

下面是我的代碼

import React from 'react'


const Button = ({children,label,onClick,type,btnClass,disabled,..rest})=>{
  let button = onClick ? (
    <button type={type} className={btnClass} onClick={onClick} 
    disabled={disabled} {...rest}>
      <span className="flex flex-row justify-center">
         {children}
         {label}
        </span>
        </button>
  ): (<button type={type} className={btnClass} 
    disabled={disabled} {...rest}>
      <span className="flex flex-row justify-center">
         {children}
         {label}
        </span>
        </button>)

        return <span>{button}</span>
};

export default Button;

測試用例:

import {mount} from 'enzyme';
import {expect} from 'chai'
describe("button component", () => {
  it("props should be available", () => {
    let props = {
      label: 'default',
      onClick: ()=>{return;}
    };
    const wrapper  = mount(<Button {...props} />);

    expect(wrapper.instance().props.label).to.be(props.label);
  });
});

錯誤: 在此處輸入圖像描述

您是否嘗試過使用shallow而不是mount 並替換to.equaltoEqual

import {shallow} from 'enzyme';
import {expect} from 'chai';
describe("button component", () => {
  it("props should be available", () => {
    let props = {
      label: 'default',
      onClick: ()=>{return;}
    };
    const wrapper  = shallow(<Button {...props} />);

    expect(wrapper.instance().props.label).toEqual(props.label);
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM