测试从元素获取html属性的函数时,Jest返回未定义

时间:2020-01-22 20:24:32

标签: typescript jestjs

我有这个功能要测试:

getAttributes(el) {
    let dataAttrs = {};
    let attributes = el.attributes;
    const dataAttributes: any = Object.values(attributes);

    for (const dataAttribute of dataAttributes) {
      let keyName = dataAttribute.name;
      let keyValue = dataAttribute.value;
      dataAttrs[keyName] = keyValue;
    }

    return dataAttrs;
}

这是我开玩笑的测试:

test('get attributes on element', () => {
  let breadcrumb = new DsBreadcrumb();
  var element = document.createElement('a');
  element.setAttribute('href', 'https://www.google.ca/');
  element.innerHTML = 'lorem ipsum lorem ispum';

  console.log(element.innerText);

  expect(breadcrumb.getAttributes(element)).toBe('Hello');
});

这就是玩笑的回报:

enter image description here

我知道我的代码可以在笑话之外运行,当我在控制台上登录dataAttributes时,我得到了以下信息: enter image description here

所以在我的代码中,当我这样做时: 让keyName = dataAttribute.name;

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

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

这是单元测试解决方案:

index.ts

export class DsBreadcrumb {
  public getAttributes(el) {
    const dataAttrs = {};
    const attributes = el.attributes;
    const dataAttributes: any = Object.values(attributes);

    for (const dataAttribute of dataAttributes) {
      const keyName = dataAttribute.name;
      const keyValue = dataAttribute.value;
      dataAttrs[keyName] = keyValue;
    }

    return dataAttrs;
  }
}

index.test.ts

import { DsBreadcrumb } from './';

describe('59867716', () => {
  describe('#getAttributes', () => {
    it('should pass', () => {
      const breadcrumb = new DsBreadcrumb();
      const mEvent = { attributes: { a: { name: 'a name', value: 'a value' } } };
      const actual = breadcrumb.getAttributes(mEvent);
      expect(actual).toEqual({ 'a name': 'a value' });
    });
  });
});

单元测试结果覆盖率100%:

 PASS  src/stackoverflow/59867716/index.test.ts (13.135s)
  59867716
    #getAttributes
      ✓ should pass (6ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        15.124s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59867716