how to partially test the shape and partially test the values of a json object?

You can do this by using chai-json-pattern plugin.

Chai JSON pattern allows you to create blueprints for JavaScript objects to ensure validation of key information. It enables you to use JSON syntax extends with easy to use validators. It came up mostly for testing API with cucumber-js but can be used in any application. Additionally, you can extend base functionality with custom validators

E.g.

const chai = require('chai');
const chaiJsonPattern = require('chai-json-pattern').default;
chai.use(chaiJsonPattern);
const { expect } = chai;

describe('64715893', () => {
  it('should pass', () => {
    const object = {
      recipe: {
        _id: Math.random().toString(),
        name: 'thing',
        usedIngredients: [Math.random() + 'whatever'],
      },
    };
    expect(object).to.matchPattern(`{
      "recipe": {
        "_id": String,
        "name": "thing",
        "usedIngredients": Array,
      },
    }`);
  });
});

test result:

  64715893
    ✓ should pass


  1 passing (50ms)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top