0

对于下面的示例,.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

我认为测试失败是因为箭头函数创建了一个新的函数引用。noop这个新函数与传入的函数有不同的引用Comp

但我想要的是,有没有类似expect.any(Function)的方法jestjs,只是断言是否wrapper包含onChange事件处理程序的任何函数?

软件包版本:

"enzyme": "^3.10.0",
"jest": "^24.9.0",
4

1 回答 1

0

老实说,我认为使用 .contains(nodeOrNodes) 是解决这种情况的好方法。

我个人的建议如下:

 let inputComponent = wrapper.find("input[placeholder]='username'");
 expect(inputComponent.length).toBe(1); // This tests your component is exists rather than contains)
 expect(inputComponent.props().onChange).toEqual(noop); //This tests onChange function  is equal your mock function

请投票,如果它对你有用

于 2020-02-03T00:04:39.923 回答