在下面的例子中,.contains(nodeOrNodes) => Boolean接口运行良好。
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我认为测试失败是因为箭头函数创建了一个新的函数引用。这个新函数与传递到Comp中的noop函数具有不同的引用。
但我想要的是,有没有像jestjs的expect.any(Function)一样的方法,只是断言wrapper是否包含onChange事件处理程序的任何函数?
包版本:
"enzyme": "^3.10.0",
"jest": "^24.9.0",发布于 2020-02-03 08:04:40
老实说,我不认为使用.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请投票,如果对你有效的话
https://stackoverflow.com/questions/59892397
复制相似问题