shahzaibkhalid
shahzaibkhalid

Reputation: 127

How to test a React ref with a callback?

Enzyme docs contains how to test a node having ref with wrapper.ref('nameOfRef'), but this only works for refs having just a string value like, if I have a node in React:

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

Then its test would be written like:

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

But if I have a ref with a callback, then how to test it? Enzyme docs [1] does not says anything about this. For example, if I have a node with a ref like this:

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

Thanks for guidance.

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

Upvotes: 5

Views: 7587

Answers (1)

Lin Du
Lin Du

Reputation: 102237

You can call the ref callback manually using wrapper.getElement()['ref'](mockRef).

E.g.

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);
  });
});

unit test result:

 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

Upvotes: 2

Related Questions