Skip to content

Instantly share code, notes, and snippets.

@Yang03
Created July 25, 2017 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yang03/8e7d95ac39ba3abc95e30c0002451f69 to your computer and use it in GitHub Desktop.
Save Yang03/8e7d95ac39ba3abc95e30c0002451f69 to your computer and use it in GitHub Desktop.
sinon.js 测试
sinon spies, stubs(stəb,存根), mocks
spies sinon.spy() //会调用原来的function
stubs //完全代替之前的function,不会执行原来的function
mocks //和stubs一样,可以用来替换整个对象以改变其行为
@Yang03
Copy link
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
Copy link
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
Copy link
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