繁体   English   中英

如何使用回调测试 React ref?

[英]How to test a React ref with a callback?

Enzyme docs 包含如何使用wrapper.ref('nameOfRef')测试具有ref的节点,但这仅适用于只有字符串值的 refs,如果我在 React 中有一个节点:

<span ref="secondRef" amount={4}>Second</span>

然后它的测试会写成:

expect(wrapper.ref('secondRef').prop('amount')).to.equal(4);

但是如果我有一个带有回调的 ref,那么如何测试它? Enzyme docs [1] 对此没有任何说明。 例如,如果我有一个带有像这样的 ref 的节点:

<SomeCustomReactElement ref={_form => form = _form} />

谢谢指导。

[1]: http://airbnb.io/enzyme/docs/api/ReactWrapper/ref.html

酶文档包含如何使用wrapper.ref('nameOfRef')测试具有ref的节点,但这仅适用于仅具有字符串值的ref,例如,如果我在React中有一个节点:

<span ref="secondRef" amount={4}>Second</span>

然后将其测试写为:

expect(wrapper.ref('secondRef').prop('amount')).to.equal(4);

但是,如果我有带回调的ref,那么如何对其进行测试? 酶文档[1]对此没有任何说明。 例如,如果我有一个带有这样的ref的节点:

<SomeCustomReactElement ref={_form => form = _form} />

感谢您的指导。

[1]: http://airbnb.io/enzyme/docs/api/ReactWrapper/ref.html

您可以使用wrapper.getElement()['ref'](mockRef)手动调用ref回调。

例如

index.tsx

import React, { Component } from 'react';

export class SomeCustomReactElement extends Component {
  doSomething() {
    console.log('do somthing');
  }
  render() {
    return <span>some custom react element</span>;
  }
}

export default class MyComponent extends Component {
  handleRef = (ref: SomeCustomReactElement) => {
    console.log('handle ref');
    ref.doSomething();
  };
  render() {
    return (
      <div>
        <SomeCustomReactElement ref={this.handleRef} />
      </div>
    );
  }
}

index.test.tsx

import React from 'react';
import { shallow } from 'enzyme';
import MyComponent, { SomeCustomReactElement } from './';

describe('48349435', () => {
  it('should handle ref', () => {
    const wrapper = shallow(<MyComponent />);
    const mRef = {
      doSomething: jest.fn(),
    };
    wrapper.find(SomeCustomReactElement).getElement()['ref'](mRef);
    expect(mRef.doSomething).toBeCalledTimes(1);
  });
});

单元测试结果:

 PASS  examples/48349435/index.test.tsx (7.984 s)
  48349435
    ✓ should handle ref (44 ms)

  console.log
    handle ref

      at Object.MyComponent.handleRef [as ref] (examples/48349435/index.tsx:14:13)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |   77.78 |      100 |      60 |   77.78 |                   
 index.tsx |   77.78 |      100 |      60 |   77.78 | 5-8               
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.273 s

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM