【问题标题】:How to test return function value如何测试返回函数值
【发布时间】:2019-12-11 01:26:09
【问题描述】:

如何测试这个函数的返回值?

handleValidatePassword = (confirmPassword) => {
    const { newPassword } = this.props;
    if (newPassword !== confirmPassword) {
      return <FormattedMessage id="some value" />;
    }
  }

如果条件正确,我需要检查此函数的返回值是否为预期值:(FormattedMessage return span with value === id)

<span> some value </span>

我正在使用浅酶进行测试

【问题讨论】:

  • 你应该更好地解释你想做什么
  • 你的问题有点不清楚。您在测试中使用什么来渲染组件(可能是酶吗?)
  • 在函数中放置console.log(changePass.alerts.notMatch);在返回之前。
  • 使用 import { shallow } from 'enzyme' 进行测试

标签: javascript html reactjs jestjs


【解决方案1】:

如果您使用 jest 或 jasmine f.e.,我个人会使用酶匹配剂。 https://github.com/FormidableLabs/enzyme-matchers/blob/master/packages/jest-enzyme/README.md#tocontainreact

import { shallow } from 'enzyme' 
import Element from './yourpath'

const wrapper = shallow(<Element />); // mount/render/shallow when applicable

//as shallow renders only one level of children components
expect(wrapper).toContainReact(<FormattedMessage id="some value" />);

//or if you want to test actually the span element you should use mount
const wrapper2 = mount(<Element />);
expect(wrapper).toContainReact(<span> some value </span>);

【讨论】:

  • 不起作用,因为在挂载组件时 不存在,我在函数内部有一个条件,所以我需要检查如果正确满足条件,函数会返回,但是感谢您提供此信息,这将对我将来有所帮助。我需要测试那个函数会返回
  • 例如——`wrapper.instance().handleValidatePassword = jest.fn(); wrapper.instance().handleValidatePassword.mockReturnValue( changePass.alerts.notMatch );` 但这对 不起作用
  • 你能在你使用这个功能的地方分享组件代码吗?代码中的这种情况是否取决于组件的状态?如果是这样,那么您可以在测试中使用 setState f.e. like here
  • 我可以验证这个函数会返回吗?就好像它独立于组件和其他东西一样
  • 或者我可以通过某种方式检查条件是否有效(例如:newPassword !== confirmPassword)
猜你喜欢
  • 2017-02-04
  • 2016-12-26
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 2012-07-07
  • 1970-01-01
  • 1970-01-01
  • 2019-12-14
相关资源
最近更新 更多