Skip to content

Proposal: assert.matchObject #50399

Closed
@arthurfiorette

Description

@arthurfiorette

What is the problem this feature will solve?

(I tried searching for related issues, but couldn't find one, sorry if this is a duplicated)

One thing I miss when using node:test and node:assert from jest related tests is the expect(A).toMatchObject(B) api. Within large production systems, a we usually have large objects with multiple deep properties, with assert.matchObject we could test the same way as assert.deepStrictEqual, but only specifying expected properties we want to test out with a much nicer DX. Obviously a assert.notMatchObject should also be present.

Current behavior:

const myObjectToTest = {
  a: 1,
  b: 2,
  c: {
    d: 3,
    e: 4,
    f: {
       g: 5
    }
  }
}

// For my specific test, I want to assert `myObjectToTest.b` and `myObjectToTest.c.f.g`.
assert.equal(myObjectToTest.b, 2);
assert.equal(myObjectToTest.c.f.g, 5);

// If I wanted to check against another object or using a object (better DX)
// I must specify ALL fields (even the one that doesn't matter for my specific test)
assert.deepStrictEqual(myObjectToTest, {
  a: 1,
  b: 2,
  c: {
    d: 3,
    e: 4,
    f: {
      g: 5
    }
  }
});

What is the feature you are proposing to solve the problem?

With assert.matchObject:

assert.matchObject(myObjectToTest, {
  b: 2,
  c: {
    f: {
      g: 5
    }
  }
});

It should ensure equality only for properties assigned to the second parameter. myObjectToTest could have 10000 other attributes or be literally the same as the second parameter, it would pass. Whenever a property declared inside the second object is not present in the first one, an AssertionError should be thrown.

Of course this is a small example that could be tested separately, but it is a perfect DX fit for large objects.

What alternatives have you considered?

I'm creating this feature request with a jest like API in mind, however any alternatives that also fixes this problem are welcome :) I'm also open to working on this, but first I need some kind of guidance :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    assertIssues and PRs related to the assert subsystem.feature requestIssues that request new features to be added to Node.js.

    Type

    No type

    Projects

    Status

    Awaiting Triage

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions