如何使用 Mocha 对接收 select 元素的 JS 函数进行单元测试?

How to unit test a JS function that receives a select element with Mocha?

我想对以下 JS 函数进行单元测试:

let convert = {};

convert.f = function f(element)
{
    options = Array.from(element.options);
    options.forEach(function (item, index) {
        item.removeAttribute('selected');
    });
}

module.exports = convert;

它应该接收一个 select DOM 元素并删除其选项的 selected 属性。

我目前正在使用 Mocha 使用以下测试代码对其进行测试:

let convert = require('../../main/webapp/WEB-INF/js/helper.js')

var assert = require('assert');

describe('Function', function() {
  describe('#f()', function() {
    it('should work', function() {
      var selectedOption = [{}]
      var options = [{}]
      var element = { className: '', tag: 't', name:'a', id:'b', selectedOptions: selectedOption, options: options };
      convert.f(element);
    });
  });
});

目前我正在 "TypeError: item.removeAttribute is not a function"。我已经知道这不是正确的方法,所以我需要帮助来理解对代码进行单元测试的最佳方法。任何帮助将不胜感激。

您需要模拟 select 包含选项数组的元素对象,其中每个选项具有以下内容:

  • 属性 命名为 selected,此 属性 将对具有 selected 属性的选项成立
  • removeAttribute 函数

select 元素对象应如下所示

const removeAttr = function() {
    this.selected = false;
};

const select = {
    options: [
      { selected: true, value: 1, removeAttribute: removeAttr  },
      { selected: true, value: 1, removeAttribute: removeAttr  },
      { selected: true, value: 1, removeAttribute: removeAttr  },
    ]
};

看到这个 demo。打开 shell 和 运行 npm test 命令。我在这个演示中使用 chai 作为断言库。

要打开 shell,在 mac 上,按 command + shift + S。在 windows 上,按右下角的 ? 图标,然后单击菜单中的键盘快捷键选项。