Imagine, for example, that I am testing a simple js class which looks like:
class Test {
static id = 0;
static defaultConfig = { default: 'value' };
static makeTest(config) {
return new Test(config);
}
constructor(config = {}) {
this.id = Test.id++;
this.config = { ...Test.defaultConfig, ...config };
}
};
I want to test the Test.makeTest
static method. I want to make sure it returns an instance of Test
, and that the instance’s config is determined by the parameter passed to Test.makeTest
. I could do the following:
describe('Test.makeTest', () => {
it('works in simple case', () => {
const test = Test.makeTest({ a: 1, b: 2 });
expect(test).toEqual(expect.any(Test));
expect(test).toHaveProperty('id', 0);
expect(test).toHaveProperty('config', expect.objectContaining({ a: 1, b: 2 }));
});
});
My question is: how can I write an equivalent test (with multiple expectations) without assigning a reference to the Test
instance?
For example it would be so nice to be able to chain .toEqual
and .toHaveProperty
…
describe('Test.makeTest', () => {
it('works in simple case', () => {
expect(Test.makeTest({ a: 1, b: 2 }))
.toEqual(expect.any(Test))
.toHaveProperty('id', 0)
.toHaveProperty('config', expect.objectContaining({ a: 1, b: 2 }));
});
});
… but this isn’t supported (these methods all return undefined
).
Overall I hope to boost the readability and lower the cognitive overhead of tests.