如何在Jest中比较两个集合而忽略元素顺序? [英] How do I compare two collections in Jest ignoring element order?
本文介绍了如何在Jest中比较两个集合而忽略元素顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在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?
推荐答案
另一种方法是使用自述文件中的示例
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屋!
查看全文