如何在忽略元素顺序的 Jest 中比较两个集合? [英] How do I compare two collections in Jest ignoring element order?
问题描述
在 Jest 中编写单元测试时,如何测试数组是否以任何顺序完全包含预期值?
When writing a unit test in Jest, how can I test that an array contains exactly the expected values in any order?
在柴,我可以写:
const value = [1, 2, 3];
expect(value).to.have.members([2, 1, 3]);
Jest 中的等效语法是什么?
What's the equivalent syntax in Jest?
推荐答案
另一种方法是使用来自 jest-community/jest-extended.
Another way is to use the custom matcher .toIncludeSameMembers()
from jest-community/jest-extended.
README 中给出的示例
Example given from the README
test('passes when arrays match in a different order', () => {
expect([1, 2, 3]).toIncludeSameMembers([3, 1, 2]);
expect([{ foo: 'bar' }, { baz: 'qux' }]).toIncludeSameMembers([{ baz: 'qux' }, { foo: 'bar' }]);
});
仅仅为一个匹配器导入一个库可能没有意义,但我发现它们还有很多其他有用的匹配器.
It might not make sense to import a library just for one matcher but they have a lot of other useful matchers I've find useful.
附加说明,如果您使用的是 Typescript,您应该导入添加到 expect
的方法的类型使用这一行:
Additional note, if you're using Typescript, you should import the types for the methods added to expect
with this line:
import 'jest-extended';
这篇关于如何在忽略元素顺序的 Jest 中比较两个集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!