簡體   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