首页 > 解决方案 > 尝试在 TypeScript 中进行单元测试

问题描述

我试图了解单元测试是如何工作的

我有这个方法:

public async parseTest(diffComponents: any[]): Promise<Map<string, string[]>> {
    const result: Map<string, string[]> = new Map();
    for (let i = 0; i < diff.length; i++) {
        const element = diff[i];
        try {
            const fileContent = fs.readFileSync("changelog.txt","UTF-8");
            const lines = fileContent.split("\n");
            const list = this.retrieve(lines, element);
            result.set(element.components, list);
        } catch (err) {
            return Promise.reject("ERROR: Cannot find file from components");
        }
    }
    return result;
}

结果的输出例如:

Map { 'toto' => [ 'toto-11' ] }

这是我的测试,但它不起作用:

describe("parse", () => {
    test("check map result", () => {
        // Given
        const array = [{ components: "toto", newVersion: "2.2", oldVersion: "2.1" }];

        // When
        const result = new ChangelogService().parseTest(array);
        const expected = new Map();
        expected.set("toto", "toto-11");
        // Then
        expect(result).toBe(expected);   // problem in this line 
    });
});

该行的错误是:

Error: expect(received).toBe(expected) // Object.is equality
Expected: Map {"toto" => "toto-11"}
Received: {}Jest

你能解释一下问题或给出更好的测试方法吗?

标签: javascripttypescriptunit-testingjestjs

解决方案


.toBe完全匹配,这意味着它必须是同一个对象。

如果您想比较对象是否包含您需要使用的相同键和值.toEqual

你的 Map 也是一个数组,你应该在expected.

该方法返回您需要解决的承诺。

describe("parse", () => {
    test("check map result", async () => { // <- add async
        // Given
        const array = [{ components: "toto", newVersion: "2.2", oldVersion: "2.1" }];

        // When
        const result = await (new ChangelogService().parseTest(array)); // <- add await
        const expected = new Map();
        expected.set("toto", ["toto-11"]); // <- wrap the value
        // Then
        expect(result).toEqual(expected); // <- change to toEqual
    });
});

然后 jasmine 将通过result并用 键逐个检查它expected


推荐阅读