如何在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';