I'm doing a simple test similar to the following:
it("Must fail", () => {
const length = person.list().length;
expect(person.add({ name: "John", age: -5, gender: 'M' })).toEqual(
expect.objectContaining({
id: expect.any(Number),
name: expect.any(String),
age: expect.any(Number),
gender: 'M' || 'F', // only 'M' or 'F'
})
);
// to ensure that a new person was added
expect(person.list().length).toEqual(length+1);
});
The return of db.add is an object with the id included. However, I would like to expect that age is not only any number, but also a number with an age greater than or equal zero.
I could use discrete values in gender or specify age: 0 || 1 || 2 || 3 || ...
, but if I want to match the gender with an specific pattern match or specify that age is in a range of allowed values, how could I do that?
I cannot use expect(age) inside, as far as I know in my research to expect something about the value of keys.
It looks like you are trying to do to much in as few lines of code as possible which puts you in this situation, try something like this:
it("should set age to 0 when provided age is lower than 0", () => {
const storedPerson = person.add({ name: "John", age: -5, gender: 'M' });
expect(storedPerson.age).toBe(0);
});
If you want to check all values but you don't want to write 5 expect
to do so, then try this:
it("should properly store new person", () => {
const length = person.list().length;
const expectedPerson = { id: expect.any(Number), name: "John", age: 0, gender: 'M' };
const storedPerson = person.add({ name: "John", age: -5, gender: 'M' });
expect(storedPerson).toEqual(expectedPerson);
expect(person.list().length).toEqual(length+1);
});
But to be honest I would recommend my first example. With the second one you would test to much in one test, checking proper validation of age, checking if id was added, checking properly assigned values and checking lists length. When that test fails you wouldn't know what went wrong based on the name of test. In unit tests, try to test as little as possible in one test.