Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check array equality with Jest

I've got a method inside the file test.ts:

public async listComponentsDiffer(lastTag: string, workDir: string): Promise<any[]> 

This method return me a array like this :

[{ components: "toto", newVersion: "2", oldVersion: "1" }]

I'm trying to use Jest and I'm doing this for check this method:

test("correct array form", () => {
    // Given
    const lastag = "";
    const workDir = ".";

    // When
    const result = ComponentsService.listComponentsDiffer(lastag, workDir);

    // Then
    const expected = [{ components: "toto", newVersion: "2", oldVersion: "1" }];
    expect(result).toBe(expected);
});

But I've got thsi error :

TypeError: test_1.test.listComponentsDiffer is not a function Jest

How can I do my test ?

like image 663
azdaj zdnakjdnaz Avatar asked Jul 26 '26 11:07

azdaj zdnakjdnaz


1 Answers

  1. This method is an instance method, not a class static method. Need to be called from an instance of the class.

  2. This method uses async/await syntax, you need to add async/await to your test case as well.

  3. Instead of using .toBe, you should use .toEqual.

Use .toEqual to compare recursively all properties of object instances (also known as "deep" equality)

E.g.

test.ts:

export class ComponentsService {
  public async listComponentsDiffer(lastTag: string, workDir: string): Promise<any[]> {
    return [{ components: 'toto', newVersion: '2', oldVersion: '1' }];
  }
}

test.test.ts:

import { ComponentsService } from './test';

describe('60667611', () => {
  test('correct array form', async () => {
    const lastag = '';
    const workDir = '.';
    const instance = new ComponentsService();

    const result = await instance.listComponentsDiffer(lastag, workDir);

    const expected = [{ components: 'toto', newVersion: '2', oldVersion: '1' }];
    expect(result).toEqual(expected);
  });
});

unit test results:

 PASS  stackoverflow/60667611/test.test.ts (7.968s)
  60667611
    ✓ correct array form (6ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.014s
like image 112
slideshowp2 Avatar answered Jul 29 '26 00:07

slideshowp2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!