Home > Net >  How to test if a method returns an array of a class in Jest
How to test if a method returns an array of a class in Jest

Time:04-02

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 getAll to return an empty array (because there aren't any entities to get), the test cannot tell you whether the array would have had Entity elements 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 said Entity is 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 have toBeTruthy, though, and we can use every to tell us if every element is an Entity:

    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 every on an empty array return true, 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.

  • Related