Skip to content

Instantly share code, notes, and snippets.

@Yang03 Yang03/sinon
Created Jul 25, 2017

Embed
What would you like to do?
sinon.js 测试
sinon spies, stubs(stəb,存根), mocks
spies sinon.spy() //会调用原来的function
stubs //完全代替之前的function,不会执行原来的function
mocks //和stubs一样,可以用来替换整个对象以改变其行为
@Yang03

This comment has been minimized.

Copy link
Owner Author

Yang03 commented Jul 25, 2017

//spies
function myFunction(condition, callback){
  if(condition){
    callback();
  }
}

describe('myFunction', function() {
  it('should call the callback function', function() {
    var callback = sinon.spy();

    myFunction(true, callback);

    assert(callback.calledOnce);
  });
});

myFunction会调用

@Yang03

This comment has been minimized.

Copy link
Owner Author

Yang03 commented Jul 25, 2017

//stubs

function saveUser(user, callback) {
  $.post('/users', {
    first: user.firstname,
    last: user.lastname
  }, callback);
}
describe('saveUser', function() {
  it('should call callback after saving', function() {

    // 我们会stub $.post,这样就不用真正的发送请求
    var post = sinon.stub($, 'post');
    post.yields();

    // 针对回调函数使用一个spy
    var callback = sinon.spy();

    saveUser({ firstname: 'Han', lastname: 'Solo' }, callback);

    post.restore();
    sinon.assert.calledOnce(callback);
  });
});

// 不会调用saveUser 发送ajax请求

@Yang03

This comment has been minimized.

Copy link
Owner Author

Yang03 commented Jul 25, 2017

describe('incrementStoredData', function() {
  it('should increment stored value by one', function() {
    var storeMock = sinon.mock(store);
    storeMock.expects('get').withArgs('data').returns(0);
    storeMock.expects('set').once().withArgs('data', 1);

    incrementStoredData();

    storeMock.restore();
    storeMock.verify();
  });
});

//可以处理一个对象

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.