简体   繁体   中英

Compare response in jest unit test case

I'm new to jest unit test case scenario, I have a scenario where in the response from the service that I called is of the below format

Artifact {
        name: 'detection-v1.zip',
        file_path: 'artifact\\bn-ds-anomalydetection-v1.zip',
        is_tenant: false,
        metadata: [
          Registerfact {
            name: 'ad',
            _meta: [Object],
            line_meta: [Object]
          },
          Registerfact {
            name: 'ad-generic',
            _meta: [Object],
            line_meta: [Object]
          }
        ]
      }

how can i compare the above response in the jest service, I was trying to create a object but the Artifact name before the object is confusing how should i proceed

The test case is

test('test processArtifact method', async()=>{
    const mockGetRestClient = jest.fn();
    
    try{
      const response = await factService.processfact(artifact)
      console.log("response---",response)
      // expect(response).toEqual()
    }
    catch(e){ }
  })

I know its silly question,but i'm confused hence posted it.

How should i create the static object to be put in.toEqual()?

You can declare a global/static var with your response object on top of file. Or better declare it in some constants file and import here.

For Comparison: Usually, if you have a simple object, you can use JSON.stringify . However, it may give error due to different order of object keys.

You should use assert for the deep comparison. There is method assert.deepEqual() which does deep comparison of objects.

an example for using assert from official docs

import assert from 'node:assert';

const obj1 = {
  a: {
    b: 1
  }
};
const obj2 = {
  a: {
    b: 2
  }
};
const obj3 = {
  a: {
    b: 1
  }
};
const obj4 = Object.create(obj1);

assert.deepEqual(obj1, obj1);
// OK

// Values of b are different:
assert.deepEqual(obj1, obj2);
// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }

assert.deepEqual(obj1, obj3);
// OK

// Prototypes are ignored:
assert.deepEqual(obj1, obj4);
// AssertionError: { a: { b: 1 } } deepEqual {}

Hope this helps, let me know if you have any questions.

You can use JSON.stringify in order to convert your object into a string and then compare this result to the one you expect.

 console.log(JSON.stringify({ name: 'detection-v1.zip', file_path: 'artifact\\bn-ds-anomalydetection-v1.zip', is_tenant: false, metadata: [ {Registerfact: { name: 'ad', _meta: {}, line_meta: {} }}, {Registerfact: { name: 'ad-generic', _meta: {}, line_meta: {} }} ] }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM