Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 测试从元素获取html属性的函数时,Jest返回undefined_Typescript_Jestjs - Fatal编程技术网

Typescript 测试从元素获取html属性的函数时,Jest返回undefined

Typescript 测试从元素获取html属性的函数时,Jest返回undefined,typescript,jestjs,Typescript,Jestjs,我想开玩笑地测试这个函数: getAttributes(el){ 设dataAttrs={}; 让属性=el.attributes; const dataAttributes:any=Object.values(属性); for(数据属性的常量数据属性){ 让keyName=dataAttribute.name; 让keyValue=dataAttribute.value; dataAttrs[keyName]=keyValue; } 返回数据属性; } 这是我的玩笑测试: test('get

我想开玩笑地测试这个函数:

getAttributes(el){
设dataAttrs={};
让属性=el.attributes;
const dataAttributes:any=Object.values(属性);
for(数据属性的常量数据属性){
让keyName=dataAttribute.name;
让keyValue=dataAttribute.value;
dataAttrs[keyName]=keyValue;
}
返回数据属性;
}
这是我的玩笑测试:

test('get attributes on element',()=>{
让breadcrumb=新的DsBreadcrumb();
var-element=document.createElement('a');
element.setAttribute('href','https://www.google.ca/');
element.innerHTML='lorem ipsum lorem ispum';
log(element.innerText);
expect(breadcrumb.getAttributes(element)).toBe('Hello');
});
这就是jest的回报:

我知道我的代码在jest之外工作,当我在控制台上记录dataAttributes时,我得到了以下信息:

因此,在我的代码中,当我这样做时: 让keyName=dataAttribute.name

keyname返回undefined,因为它找不到html元素的值。在上面的照片中,你可以看到我需要的信息,但出于某种原因,它不是一个名为_的MockAttr对象


非常感谢您的帮助

以下是单元测试解决方案:

index.ts

导出类DsBreadcrumb{
公共属性(el){
常量dataAttrs={};
常量属性=el属性;
const dataAttributes:any=Object.values(属性);
for(数据属性的常量数据属性){
const keyName=dataAttribute.name;
const keyValue=dataAttribute.value;
dataAttrs[keyName]=keyValue;
}
返回数据属性;
}
}
index.test.ts

从“/”导入{DsBreadcrumb};
描述('59867716',()=>{
描述('#getAttributes',()=>{
它('应该通过',()=>{
const breadcrumb=新的DsBreadcrumb();
const-mEvent={attributes:{a:{name:'a name',value:'a value'}};
const actual=breadcrumb.getAttributes(mEvent);
expect(实际).toEqual({'a name':'a value'});
});
});
});
100%覆盖率的单元测试结果:

通过src/stackoverflow/59867716/index.test.ts(13.135s)
59867716
#获取属性
✓ 应通过(6ms)
----------|----------|----------|----------|----------|-------------------|
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s|
----------|----------|----------|----------|----------|-------------------|
所有文件| 100 | 100 | 100 | 100 ||
index.ts | 100 | 100 | 100 | 100 ||
----------|----------|----------|----------|----------|-------------------|
测试套件:1个通过,共1个
测试:1项通过,共1项
快照:共0个
时间:15.124秒

源代码:

哇,好的,谢谢,这很好用。我有两个问题:你为什么在另一个下面加上描述?为什么jest返回mockAttr,有什么原因吗。多个
描述
是一种层次分类,您可以将它们视为PC系统的某种文件夹结构。当您有很多测试套件和测试用例时,这一点就很清楚了。2.返回值是通过执行
getAttributes
方法获得的,如果您更改了逻辑,则可以更改结果。这不是武断的
mEvent
is input=>
getAttributes
=>get
{'a name':'a value'}
输出