我试图了解单元测试的工作原理
我有这个方法:
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
您能说明问题还是提供更好的测试方法?
答案 0 :(得分:0)
.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
});
});
然后,茉莉花将穿过result
,并用expected
逐个检查它。