如何使用单元测试检查字符串是否恰好出现 1 次?

How to check for exactly 1 occurence of a string with unit test?

我正在使用 enzyme 和 chai 为我的 reactjs-app 创建一个单元测试:

const wrapper = shallow(
    <MyComp {...props}>
    </MyComp>
);

expect(wrapper.debug()).to.contain("hello");

我如何断言单词 'hello' 正好出现 1 次?

我建议测试组件的完整呈现:

// GIVEN
const expectedElement = shallow(<div>Hello</div>);

// WHEN
const actualElement = shallow(<MyComp {...props} />);

// THEN
expect(actualElement.html()).to.equal(expectedElement.html());

它比 contains 方法提供更好的覆盖率。但是有时您需要使用正则表达式来清除 React 空 HTML 模板或生成 CSS 类(如果您或您的第三方组件正在使用它们)。

如果您使用 Jest,还有 library/plugin 可以预先生成预期元素,您可以将其签入源代码管理。每次测试 运行 都会将实际渲染与此预渲染组件进行比较。但是我自己并没有使用这种方法。