【问题标题】:React - unit testing with a setup functionReact - 使用设置功能进行单元测试
【发布时间】:2017-02-09 16:25:09
【问题描述】:

我有以下情况:

describe('API - Input component', () => {
   describe('Input element', () => {
    it('should have a modifier to its class if data entered is erroneous', () => {
      const wrapper = shallow(<Input error="Invalid data" />);

      expect(wrapper.find('input').props().className).toBe('form-field__input form-field__input--error');
    });
  });
});

这工作得很好。只要我将一些数据传递给我的 error 道具,就应该期望一个修饰符类并且测试通过。

现在,我想实现相同的目标,但使用设置功能。像这样:

function setup () {
  const props = {
    error: {}
  };

  return shallow(<Input {...props} />);
}

describe('API - Input component', () => {
   describe('Input element', () => {
    it('should have a modifier to its class if data entered is erroneous', () => {
      const wrapper = setup(how do I pass my props here?!);

      expect(wrapper.find('input').props().className).toBe('form-field__input form-field__input--error');
    });
  });
});

谢谢!

【问题讨论】:

    标签: unit-testing reactjs mocha.js enzyme


    【解决方案1】:

    const wrapper = setup(如何在这里传递我的道具?!);

    答案很简单,道具本身就是 Literal Object {prop1: value1, prop2: value2 ,... , propN: valueN} :

      const wrapper = setup({error: 'Invalid data'});
    

    知道假设setup 应该是:

    function setup (props) {
      return shallow(<Input {...props} />);
    }
    

    如果您想要 setup 中的默认道具,请使用 Object.assign 使用参数的道具扩展 setup 中的默认道具。

    function setup (props) {
      const defaultPropsOfSetup = {
        error : 'Invalid error'
      };
      props = Object.assign(defaultPropsOfSetup, props); 
      return shallow(<Input {...props} />);
    }
    

    【讨论】:

    • 欢迎 ? ? ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 2018-02-25
    • 2017-04-14
    • 1970-01-01
    相关资源
    最近更新 更多