Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sinon 学习 #21

Open
fish519 opened this issue Aug 16, 2019 · 1 comment
Open

sinon 学习 #21

fish519 opened this issue Aug 16, 2019 · 1 comment

Comments

@fish519
Copy link
Owner

fish519 commented Aug 16, 2019

No description provided.

@fish519
Copy link
Owner Author

fish519 commented Aug 16, 2019

const sinon = require('sinon');

// spies 主要用于收集函数的调用信息
const spy = sinon.spy();
spy('hello', 'world');
console.log(spy.firstCall.args) // [ 'hello', 'world' ]

const user = {
setName: function(name){
this.name = name;
}
}
const setNameSpy = sinon.spy(user, 'setName');
user.setName('fish');
console.log(setNameSpy.callCount); // 1
setNameSpy.restore();

// 使用 stub 的时候原是函数就不会被执行
const stub = sinon.stub();
stub('hello');
console.log(stub.firstCall.args);

// stub 常用场景是验证一个函数是否使用特定的参数
// sinon.assert.calledWith(stubFn, expectedParams);
function saveUser(user, callback) {
$.post('/users', {
first: user.firstname,
last: user.lastname
}, callback);
}

// describe('saveUser', function() {
// it('should send correct parameters to the expected URL', function() {

// //We'll stub $.post same as before
// var post = sinon.stub($, 'post');

// //We'll set up some variables to contain the expected results
// var expectedUrl = '/users';
// var expectedParams = {
// first: 'Expected first name',
// last: 'Expected last name'
// };

// //We can also set up the user we'll save based on the expected data
// var user = {
// firstname: expectedParams.first,
// lastname: expectedParams.last
// }

// saveUser(user, function(){} );
// post.restore();

// sinon.assert.calledWith(post, expectedUrl, expectedParams);
// });
// });

// mock 可以定义期望的结果和期望的行为

// 最佳实践,使用sinon.test()

// spy本质是一个函数wrapper
function createSpy(targetFunc) {
var spy = function() {
spy.args = arguments;
spy.returnValue = targetFunc.apply(this, arguments);
return spy.returnValue;
};
return spy;
}
const sum = (a,b) => a+b;
const syiedSum = createSpy(sum);
syiedSum(10,5)
console.log(syiedSum.args); // [Arguments] { '0': 10, '1': 5 }
console.log(syiedSum.returnValue); // 15

// stub 其实就是替换
const myStub = () => {console.log('stub fun');}
const package = {
$: () => {
console.log('$ fun');
}
}
package.$(); // $ fun
package.$ = myStub;
package.$(); // stub fun

地址: https://blog.kazaff.me/2016/11/11/%E8%AF%91-Sinon%E5%85%A5%E9%97%A8%EF%BC%9A%E5%88%A9%E7%94%A8Mocks%EF%BC%8CSpies%E5%92%8CStubs%E5%AE%8C%E6%88%90javascript%E6%B5%8B%E8%AF%95/#%E8%AF%91%E6%96%87

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant