如何在Jest单元测试中对比Artifact类型的返回结果?
解决Jest测试中Artifact实例的对比问题
你看到控制台里的Artifact { ... }只是类实例的字符串展示形式,本质上这个返回结果是一个包含指定属性的对象实例。在Jest的toEqual()中对比时,有几种可行的方式:
方式1:直接用类创建实例对比(如果能引入Artifact类)
如果你的测试环境中可以导入Artifact和Registerfact类,直接创建对应实例并设置属性,就能和返回结果精准匹配:
// 假设已导入Artifact和Registerfact类 test('test processArtifact method', async()=>{ const mockGetRestClient = jest.fn(); try{ const response = await factService.processfact(artifact); // 构造预期的metadata数组元素 const meta1 = new Registerfact(); meta1.name = 'ad'; meta1._meta = {/* 填入实际返回的_meta对象内容 */}; meta1.line_meta = {/* 填入实际返回的line_meta对象内容 */}; const meta2 = new Registerfact(); meta2.name = 'ad-generic'; meta2._meta = {/* 填入实际返回的_meta对象内容 */}; meta2.line_meta = {/* 填入实际返回的line_meta对象内容 */}; // 构造预期的Artifact实例 const expected = new Artifact(); expected.name = 'detection-v1.zip'; expected.file_path = 'artifact\\bn-ds-anomalydetection-v1.zip'; expected.is_tenant = false; expected.metadata = [meta1, meta2]; expect(response).toEqual(expected); } catch(e){ throw e; // 抛出错误,避免测试用例静默失败 } })
方式2:用普通对象直接匹配(无需依赖类)
Jest的toEqual()会递归对比对象的所有可枚举属性值,不管对象是不是类实例。所以你可以直接写一个包含对应属性的普通对象来对比:
test('test processArtifact method', async()=>{ const mockGetRestClient = jest.fn(); try{ const response = await factService.processfact(artifact); const expected = { name: 'detection-v1.zip', file_path: 'artifact\\bn-ds-anomalydetection-v1.zip', is_tenant: false, metadata: [ { name: 'ad', _meta: {/* 填入实际返回的_meta对象内容 */}, line_meta: {/* 填入实际返回的line_meta对象内容 */} }, { name: 'ad-generic', _meta: {/* 填入实际返回的_meta对象内容 */}, line_meta: {/* 填入实际返回的line_meta对象内容 */} } ] }; expect(response).toEqual(expected); } catch(e){ throw e; } })
方式3:部分匹配(适合嵌套对象复杂的场景)
如果_meta和line_meta结构复杂,不需要精准对比所有字段,可以用expect.objectContaining和expect.arrayContaining做部分匹配:
test('test processArtifact method', async()=>{ const mockGetRestClient = jest.fn(); try{ const response = await factService.processfact(artifact); expect(response).toEqual(expect.objectContaining({ name: 'detection-v1.zip', file_path: 'artifact\\bn-ds-anomalydetection-v1.zip', is_tenant: false, metadata: expect.arrayContaining([ expect.objectContaining({ name: 'ad' }), expect.objectContaining({ name: 'ad-generic' }) ]) })); } catch(e){ throw e; } })
内容的提问来源于stack exchange,提问作者Swarup Chavan
相关产品推荐
相关产品推荐

