如何使用回调测试React引用?

时间:2018-01-19 20:57:42

标签: reactjs unit-testing callback jestjs enzyme

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

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

然后它的测试将被写成:

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

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

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

感谢您的指导。

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

2 个答案:

答案 0 :(得分:2)

这里很好地介绍了测试参考:https://reactjs.org/blog/2016/11/16/react-v15.4.0.html#mocking-refs-for-snapshot-testing

(最好在apt-cache search ros-kinetic之后的React.createRef使用16.3,如下所述:https://reactjs.org/docs/refs-and-the-dom.html,但相同的测试示例有效)

答案 1 :(得分:0)

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

例如

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