我有以下功能需要测试。
export function buildOptions(options) {
var oList=[];
for (var i=0; i < options.length; i++) {
oList.push (
<option key={"optId"+i} value={options[i]["id"]}>
{options[i]["name"]}
</option>
)
}
return oList;
}
我有一个如下的测试用例
it ('should return an array containing the populated options', () => {
let teams = [{"name":"A","id":1},{"name":"B","id":2}]
expect(JSON.stringify(Helper.buildOptions(teams))).toMatch(
JSON.stringify([<option value={1}>A</option>, <option value={2}>B</option>])
);
});
我收到错误消息,因为期望的响应和收到的响应之间的键 有所不同。您能否让我知道如何克服错误/模拟按键?
要匹配的预期值:
"[{\"type\":\"option\",\"key\":null,\"ref\":null,\"props\":{\"value\":1,\"children\":\"A\"},\"_owner\":null,\"_store\":{}},{\"type\":\"option\",\"key\":null,\"ref\":null,\"props\":{\"value\":2,\"children\":\"B\"},\"_owner\":null,\"_store\":{}}]"
已收到:
"[{\"type\":\"option\",\"key\":\"optId1\",\"ref\":null,\"props\":{\"value\":1,\"children\":\"A\"},\"_owner\":null,\"_store\":{}},{\"type\":\"option\",\"key\":\"optId2\",\"ref\":null,\"props\":{\"value\":2,\"children\":\"B\"},\"_owner\":null,\"_store\":{}}]"
答案 0 :(得分:1)
您的选项缺少key
值,因此不匹配。也许尝试一下:
it ('should return an array containing the populated options', () => {
const teams = [
{ "name": "A", "id": 1 },
{ "name": "B", "id": 2 }
];
const EXPECTED_OUTPUT = JSON.stringify([
<option key="optId1" value={1}>A</option>,
<option key="optId2" value={2}>B</option>
]);
expect(JSON.stringify(Helper.buildOptions(teams))).toMatch(EXPECTED_OUTPUT);
});
更新
有很多测试方法,如果要检查结果的长度,可以使用.toHaveLength()
,如下所示:
it('should return an array containing the populated options', () => {
const teams = [
{ "name": "A", "id": 1 },
{ "name": "B", "id": 2 }
];
const result = Helper.buildOptions(teams);
// Check if option exist and have length of 2
expect(result).toBeTruthy();
expect(result).toHaveLength(2);
// Check if the options is as expected
expect(result[0]).toEqual(<option key="optId1" value={1}>A</option>);
expect(result[1]).toEqual(<option key="optId2" value={2}>B</option>);
});
有关Jest测试的更多文档-预期:https://jestjs.io/docs/en/expect