简体   繁体   English

使用setInterval测试函数时,Mocha和Chai测试失败

[英]Mocha and Chai test fails when testing function with setInterval

I'm new to TDD and working with Mocha and Chai. 我是TDD的新手,并与Mocha和Chai合作。 I have created a test that passes when a value is increased, but when that increase is put within a setInterval, it fails. 我创建了一个在值增加时传递的测试,但是当该增加放在setInterval中时,它会失败。 The objective of this code is to have something move across the screen. 此代码的目标是让某些内容在屏幕上移动。

function startMovingThing(){
    var position = setInterval(function() {
        moveThing(10);
    }, 100);
}

function moveThing(number){
    thing.position += number;
    thingOnScreen.style.left = thing.position + 'px';
}

test: 测试:

describe('Thing', function() {

    it('should increase position', function(){
        assert.increases(startMovingThing, thing, 'position');
    });

});

How can I get this test (or what should the test be) to pass? 如何通过此测试(或测试应该是什么)?

I don't want moveThing() to be outside of the interval, because if the interval is cleared and the function is called, the thing should not move. 我不希望moveThing()超出间隔,因为如果间隔被清除并且函数被调用,那么事物就不应该移动。

Ok, the problem is that you're using setInterval which is async and you're trying to assert that the value was changed in a synchronous way. 好吧,问题是你正在使用异步的setInterval,并且你试图断言值是以同步方式改变的。

Here's a modified version of your test, using sinonjs to simulate that the time passed. 这是测试的修改版本,使用sinonjs来模拟时间的流逝。

var assert = require('chai').assert;
var sinon = require('sinon');

var thing = { position: 0 }
var thingOnScreen = { style: { left: '' } };

function startMovingThing(){
    var position = setInterval(function() {
        moveThing(10);
    }, 100);
}

function moveThing(number){
    thing.position += number;
    thingOnScreen.style.left = thing.position + 'px';
}

describe('Thing', function() {

  beforeEach(function() {
    this.clock = sinon.useFakeTimers();
  });

  afterEach(function() {
    this.clock = sinon.restore();
  });

  it('should increase position', function(){
    startMovingThing();
    this.clock.tick(101);
    assert.equal(thing.position, 10);
  });
});

In summary, sinonjs is replacing the global functionality of setInterval and is executing the code without having to wait for the specified milliseconds. 总之,sinonjs正在替换setInterval的全局功能,并且无需等待指定的毫秒即可执行代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM