javascript - 尝试在 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
你能解释一下问题或给出更好的测试方法吗?
解决方案
.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
。
推荐阅读
- javascript - 不能使用 `Authorization: Token xxx` 标头作为请求数据的标识
- correlation - 重新编码 p 值
- python - 如何在不同类的实例之间传递相同的变量(可迭代)(从同一个父类继承)
- javascript - 如何从 React Js 中的 API 响应中获取 HTML 标签?
- php - Laravel Mail Smtp php_network_getaddresses: getaddrinfo failed: Name or service not known
- if-statement - ARRAYFORMULA 如果相关则输入数据,但如果不相关则允许用户输入
- powerbi-desktop - 有条件地获取多列的不同值列表
- c - 在列表上实现冒泡排序时出现分段错误
- javascript - 如何使用正则表达式使我的代码简洁明了
- orocommerce - 向产品实体添加多个文件属性时,它在 prod 中工作,但在 dev 中抛出 NoSuchPropertyException