Search code examples
javascriptnode.jsjestjsnestjs

How to expect different values from common properties in object jest


        expect(response.body).toEqual(
          expect.objectContaining({ ...result, passsword: expect.any(String) }),
        );

here is my screen with problem

Hello everybody!

I am trying to e2e testing and want to expect some data from recieved object. Does anybody know how to expect different values using common keys in object?


Solution

  • If I understand your question correctly, then you're asking "how can I assert the shape of the data without asserting the values".

    If so, there's a number of different ways to do that such as:

    expect(response.body).toStrictEqual(expect.objectContaining({
      createdAt: expect.any(String),
      email: expect.any(String),
      // etc...
    });
    
    expect(Object.keys(response.body)).toStrictEqual(
      expect.arrayContaining(
        [ 
          'createdAt',
          email',
          /// etc... 
        ]
      )
    );
    

    But since you've already demonstrated you know how to utilize that pattern, I suspect I might be misinterpreting your question.

    Part of my confusion is that if the values you're getting back are not matching the values you provided, then that's usually a cue to rewrite the test to assert that it matches the expected values (or if you cannot control the expected values because you're doing E2E, then the test itself shouldn't be structured to pass or fail based on the exact value of the values, and instead should be structured to pass or fail based on the shape of the data).

    Usually Jest is used for unit testing and limited integration testing, if you're doing true end-to-end across multiple services, you might want to consider changing what tools you're using. Hope this helps.