使用 Jest 检查数组相等性

azd*_*naz 5 javascript unit-testing typescript jestjs

我在文件 test.ts 中有一个方法:

public async listComponentsDiffer(lastTag: string, workDir: string): Promise<any[]> 
Run Code Online (Sandbox Code Playgroud)

这个方法返回一个像这样的数组:

[{ components: "toto", newVersion: "2", oldVersion: "1" }]
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用 Jest,我这样做是为了检查此方法:

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);
});
Run Code Online (Sandbox Code Playgroud)

但我有这个错误:

TypeError: test_1.test.listComponentsDiffer is not a function Jest
Run Code Online (Sandbox Code Playgroud)

我该如何进行测试?

sli*_*wp2 9

    \n
  1. 该方法是实例方法,而不是类静态方法。需要从类的实例中调用。

    \n
  2. \n
  3. 该方法使用async/await语法,需要添加async/await到您的测试用例中。

    \n
  4. \n
  5. .toBe您应该使用而不是使用.toEqual使用。

    \n
  6. \n
\n
\n

使用 .toEqual 递归比较对象实例的所有属性(也称为“深度”相等)

\n
\n

例如

\n

test.ts:

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

test.test.ts:

\n
import { ComponentsService } from \'./test\';\n\ndescribe(\'60667611\', () => {\n  test(\'correct array form\', async () => {\n    const lastag = \'\';\n    const workDir = \'.\';\n    const instance = new ComponentsService();\n\n    const result = await instance.listComponentsDiffer(lastag, workDir);\n\n    const expected = [{ components: \'toto\', newVersion: \'2\', oldVersion: \'1\' }];\n    expect(result).toEqual(expected);\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

单元测试结果:

\n
 PASS  stackoverflow/60667611/test.test.ts (7.968s)\n  60667611\n    \xe2\x9c\x93 correct array form (6ms)\n\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        9.014s\n
Run Code Online (Sandbox Code Playgroud)\n