当所包含的react元素具有箭头函数事件处理程序时,如何使用.contains(nodeOrNodes)API?

问题描述 投票:0回答:1

对于下面的示例,.contains(nodeOrNodes) => Boolean API正常工作。

index.tsx

import React from 'react';

const Comp = ({ onChange }) => (
  <form>
    <input type="text" placeholder="username" onChange={onChange} />
  </form>
);

export default Comp;

index.test.tsx

import React from 'react';
import { shallow } from 'enzyme';
import Comp from '.';

describe('Comp', () => {
  it('should render', () => {
    const noop = () => null;
    const wrapper = shallow(<Comp onChange={noop} />);
    expect(
      wrapper.contains(
        <form>
          <input type="text" placeholder="username" onChange={noop} />
        </form>,
      ),
    ).toBeTruthy();
  });
});

单元测试结果:

 PASS  src/stackoverflow/46133847/02/index.test.tsx
  Comp
    ✓ should render (13ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.tsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.754s, estimated 24s

但是,如果我使用箭头功能更改了onChange事件处理程序:

index.ts

import React from 'react';

const Comp = ({ onChange }) => (
  <form>
    <input type="text" placeholder="username" onChange={(e) => onChange(e)} />
  </form>
);

export default Comp;

单元测试将失败。

 FAIL  src/stackoverflow/46133847/02/index.test.tsx
  Comp
    ✕ should render (18ms)

  ● Comp › should render

    expect(received).toBeTruthy()

    Received: false

      13 |         </form>,
      14 |       ),
    > 15 |     ).toBeTruthy();
         |       ^
      16 |   });
      17 | });
      18 | 

      at Object.it (src/stackoverflow/46133847/02/index.test.tsx:15:7)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        7.689s, estimated 25s

我认为测试失败,因为箭头函数创建了新的函数引用。此新功能与传递到noopComp函数具有不同的引用。

但是我想要的是,有没有办法像expect.any(Function)jestjs,只是断言wrapper是否包含onChange事件处理程序的任何功能?

打包版本:

"enzyme": "^3.10.0",
"jest": "^24.9.0",
reactjs typescript unit-testing jestjs enzyme
1个回答
0
投票

坦白地说,我没有[[not

© www.soinside.com 2019 - 2024. All rights reserved.