小编tpg*_*tin的帖子

测试JavaScript单击使用Sinon的事件

我正在尝试生成一些测试,以便能够更好地理解如何使用Mocha,Chai,Sinon和jQuery的组合来测试DOM事件.我想检查单击div元素时是否正确触发了警报功能.我知道HTML元素的设置是正确的jQuery,但我不完全确定如何为下面的代码生成传递测试.特别奇怪的是,我在浏览器中打开HTML文件时出现对话,所以我知道'$('#thingy')行.触发器('click')'正在做我期望的事情.我目前得到以下内容,'TypeError:对象不是函数'

我的测试文件的相关部分,tests.js

describe('DOM tests - div element', function() {
$("body").append("<div id='thingy'>hello world</div>")
$('#thingy').attr('class', 'thingy');
$('#thingy').click(function() { alert( "I've been clicked!" ); });


it('should have called alert function', function () {
  var spy = sinon.spy(alert);
  $('#thingy').trigger('click')
  sinon.assert(spy.called);
});
Run Code Online (Sandbox Code Playgroud)

我的HTML文件非常标准,index.html

<!doctype html>
<html>
<head>
    <title>Tests</title>
    <link rel="stylesheet" href="mocha.css" />
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
    <div id="mocha"></div>
    <script src="mocha.js"></script>
    <script src="chai.js"></script>
    <script src="sinon-1.10.2.js"></script>
    <script>
        mocha.ui('bdd');
        mocha.reporter('html');
        var expect = chai.expect;
    </script>
    <script src="tests.js"></script>
    <script>
        mocha.run();
    </script>
</body>
Run Code Online (Sandbox Code Playgroud)

javascript bdd mocha.js sinon chai

8
推荐指数
1
解决办法
1万
查看次数

使用Sinon在D3中测试Mouseover事件

我在试图让我的测试通过时遇到了麻烦.我希望能够使用间谍来检查鼠标悬停事件是否被正确调用.目前我收到以下错误,"错误:预计至少被调用一次,但从未被调用".我的部分困惑与d3和jQuery选择器之间的差异有关,我非常乐意使用后者,但我不确定如何在测试中正确使用前者来获得我想要的结果.

我的依赖是d3,jQuery,mocha,chai,sinon和sinon-chai.

我的index.html文件中的相关代码,

<script src="fixtures.js"></script>
<div id="mocha"></div>
<script src="mocha.js"></script>
<script src="chai.js"></script>
<script src="sinon-chai.js"></script>
<script src="sinon-1.10.2.js"></script>
<script>
    mocha.ui('bdd');
    mocha.reporter('html');
    var expect = chai.expect;
 </script>
 <script src="tests.js"></script>
 <script>
    mocha.run();
</script>
Run Code Online (Sandbox Code Playgroud)

fixtures.js,

var path = svg.selectAll("path")
          .data(pie(data))
          .enter().append("path").attr("class", "path")
          .style("fill", function(d, i) { return color(i); })
          .attr("d", arc)
          .on("mouseover", function() { d3.select(this).style("fill", "#ff0000"); })
          .on("mouseout" , function() { d3.selectAll("path").style("fill", function(d, i) { return color(i); }); });

//  I wanted to test my understanding of d3 selectors
var path_one = d3.select('.path').attr("id", "path_one"); 
Run Code Online (Sandbox Code Playgroud)

tests.js,

describe('Donut …
Run Code Online (Sandbox Code Playgroud)

javascript bdd jquery sinon d3.js

7
推荐指数
1
解决办法
2334
查看次数

标签 统计

bdd ×2

javascript ×2

sinon ×2

chai ×1

d3.js ×1

jquery ×1

mocha.js ×1