I'm going to test a method (using TypeScript language) to make sure it returns an array of a class.
Here is my code:
it('should return an array of Entity class', async () => {
expect(await service.getAll()).toBeInstanceOf(Entity[]);
});
But it shows the following error message at []:
An element access expression should take an argument.
CodePudding user response:
Since Jest tests are runtime tests, they only have access to runtime information. You're trying to use a type, which is compile-time information. TypeScript should already be doing the type aspect of this for you. (More on that in a moment.)
The fact the tests only have access to runtime information has a couple of ramifications:
If it's valid for
getAllto return an empty array (because there aren't any entities to get), the test cannot tell you whether the array would have hadEntityelements in it if it hadn't been empty. All it can tell you is it got an array.In the non-empty case, you have to check every element of the array to see if it's an
Entity. You've saidEntityis a class, not just a type, so that's possible. I'm not a user of Jest (I should be), but it doesn't seem to have a test specifically for this; it does havetoBeTruthy, though, and we can useeveryto tell us if every element is anEntity:it('should return an array of Entity class', async () => { const all = await service.getAll() expect(all.every(e => e instanceof Entity)).toBeTruthy(); });Beware, though, that all calls to
everyon an empty array returntrue, so again, that empty array issue raises its head.
If your Jest tests are written in TypeScript, you can improve on that by ensuring TypeScript tests the compile-time type of getAll's return value:
it('should return an array of Entity class', async () => {
const all: Entity[] = await service.getAll()
// ^^^^^^^^^^
expect(all.every(e => e instanceof Entity)).toBeTruthy();
});
TypeScript will complain about that assignment at compile time if it's not valid, and Jest will complain at runtime if it sees an array containing a non-Entity object.
But jonrsharpe has a good point: This test may not be useful vs. testing for specific values that should be there.
