fish519 / note

Write down problems encountered during development and take notes on how to solve them
0 stars 0 forks source link

sinon 学习 #21

Open fish519 opened 5 years ago

fish519 commented 5 years ago

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