我一直在努力测试JS和DOM元素,最终找到了可以帮助测试DOM元素的Karma。然而,我目前所做的一切都无法正常工作。非常感谢任何帮助。
我一直在使用这个教程:http://www.bradoncode.com/blog/2015/02/27/karma-tutorial/ ,但无法使其正常工作...
JS:
我一直在使用这个教程:http://www.bradoncode.com/blog/2015/02/27/karma-tutorial/ ,但无法使其正常工作...
JS:
window.calculator = window.calculator || {};
(function() {
var result;
var adding = function(one, two) {
var one1 = document.forms["myForm"]["one"].value;
var two2 = document.forms["myForm"]["two"].value;
var one=parseFloat(one.replace(/\,/g,''));
var two=parseFloat(two.replace(/\,/g,''));
result = parseInt(one1) + parseInt(two2);
console.log(result);
var number = document.getElementById("number");
number.innerHTML = result;
console.log(one, two, result)
return result;
}
window.calculator.init = function() {
document.getElementById('add').addEventListener('click', adding);
};
})();
HTML:
<body>
<form name="myForm">
<h4>numner 1</h4>
<input type="text" name="one" id="one"></input>
<h4>number 2</h4>
<input type="text" name="two" id="two"></input>
<input type="button" id="add">
</form>
<p id="number"> </p>
<script type="text/javascript" src="public/adder.js"></script>
<script>
calculator.init()
</script>
</body>
</html>
测试规范:
beforeEach(function() {
var fixture = '<div id="fixture"> <input type="text" name="one" id="one">' +
'<input type="text" name="two" id="two">' +
'<input type="button" id="add" >' +
'<p id="number"> </p></div>';
document.body.insertAdjacentHTML(
'afterbegin',
fixture);
});
// remove the html fixture from the DOM
afterEach(function() {
document.body.removeChild(document.getElementById('fixture'));
});
// call the init function of calculator to register DOM elements
beforeEach(function() {
window.calculator.init();
});
it('should return 3 for 1 + 2', function() {
var x = document.getElementById('one').value = 1;
var y = document.getElementById('two').value = 2;
document.getElementById('add').click();
expect(document.getElementById('number').innerHTML).toBe('3');
});
document.getElementById('add').click()
对你无效吗?我看到你已经将其注释掉了,我猜想你已经尝试过了? - tehbeardedonemyForm
。您的测试仅知道您提供的fixture
元素。从外观上看,fixture
元素需要与您想要测试的元素完全相同。我敢打赌,如果您在fixture
中添加myForm
的 HTML,则它将开始工作。 - tehbeardedone