by

## Where communities thrive

• Join over 1.5M+ people
• Join over 100K+ communities
• Free without limits
• Create your own community
##### Activity
Michael Bradley
@michaelsbradleyjr
also, in the it block, you should be calling the spy not the original function
and that’s the problem, hold on will get it to work
Michael Bradley
@michaelsbradleyjr

let countToZero = (n) => {
if (n <= 0)
// ^ 5..4..3..2..1..0 = 6 calls
return 0;
else
return countToZero(n - 1);
};

describe('countToZero', () => {
const testN = 5;

let countSpy, origFn;

beforeEach(() => {
origFn      = countToZero;
countToZero = sinon.spy(countToZero);
});
afterEach(() => {
countToZero = origFn;
});

it('should call itself each time it counts down to zero', () => {
countToZero(testN);

expect(countToZero.callCount).to.equal(6);
});

});

whoops, forgot to wrap in 

let countToZero = (n) => {
if (n <= 0)
// ^ 5..4..3..2..1..0 = 6 calls
return 0;
else
return countToZero(n - 1);
};

describe('countToZero', () => {
const testN = 5;

let countSpy, origFn;

beforeEach(() => {
origFn      = countToZero;
countToZero = sinon.spy(countToZero);
});
afterEach(() => {
countToZero = origFn;
});

it('should call itself each time it counts down to zero', () => {
countToZero(testN);

expect(countToZero.callCount).to.equal(6);
});

});

whoops, sorry for the dupe
reidblomquist
@reidblomquist
no worries! we're going to give it a whirl
Michael Bradley
@michaelsbradleyjr
anyway, that should work
reidblomquist
@reidblomquist
thank you
Michael Bradley
@michaelsbradleyjr
Amal Hussein
@nomadtechie
hi all -- I just read through this thread sinonjs/sinon#831 and I have the same issue -- but for React components.
I would like to stub out an es6 class method which was declared with a fat arrow. I would like to stub methods when testing the render output.
I have to use React's 'renderIntoDocument' which instantiates the class.
any advice on this use case?
Amal Hussein
@nomadtechie
I was going to a file a question in the react repo -- but someone else has the same open and unanswered question: facebook/react#9396
Maxim Fainberg
@burnall

Hi,
I try to stub ES6 exports and it is not working for some important cases.

// try-sinon.js
export function foo() {
return 22;
}

export const bar = () => 44;

function aa() {
return 'aa';
}

export {
aa
}

// test.spec.js
import * as all from 'try-sinon';

stub(all, 'foo').returns(1000); // This stub works: all.foo() === 1000
stub(all, 'bar').returns(1001); // No luck: all.bar() === 44
stub(all, 'aa').returns('aab'); // Too bad: all.aa() === 'aa'

I use latest sinon, webpack with babel (preset-es2015' - {'modules': false})
Any ideas how to make it work? Thanks.

Łukasz Kużyński
@wookieb
@burnall Can you show code generated by babel?
Maxim Fainberg
@burnall
@wookieb Sure
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony export (immutable) */ __webpack_exports__["foo"] = foo;
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bar", function() { return bar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "aa", function() { return aa; });
Łukasz Kużyński
@wookieb

Just looked at implementation of webpack_require.d

if(!__webpack_require__.o(exports, name)) {
Object.defineProperty(exports, name, {
configurable: false,
enumerable: true,
get: getter
});
}

Webpack defines it as getter which is correct behavior since es6 modules export bindings not values.

I suggest to try other tools like proxyquire etc.

Maxim Fainberg
@burnall
Good point, I thought about proxyquire too.
But it means that sinon stubs are not very helpful since I can't rely on them only
Łukasz Kużyński
@wookieb
That's not sinon problem obviously. I would rather say that direct mocking imported modules is a bad practice IMHO. I suggest to rely on standard OOP approaches (dependency injection container) that work exceptionally well.
Maxim Fainberg
@burnall
Yes, but better to be paradigm agnostic, functional style at least not less popular nowadays than object-oriented. Not good to use two libraries for stubbing of different application parts.
Chris
@ImTheDeveloper

Anyone know why my sinon spy doesnt work in ava if I reference the function being spied on as as just an internal reference e.g. main but passes when I use module.exports.main
My test is as follows

test.serial('preProcessing should call our main function with mails', (t) => {
const spy = sinon.spy(app.main);
app.main = spy;
app.preProcessing(null, [mockdata.ParsedPAMail]);
console.log(app.main);
t.true(app.main.called);
});

The module exports for app are:

module.exports = { init, main, preProcessing };

If I use the following to call main it works:

  if (mails.length > 0) {
return module.exports.main(mails);
}

If I change that return to just be main(mails); it doesnt work. The spy suggests the "main" function hasn't been called even though I can step through and see that it is. Is this to do with caching of the "app" module when I require it in? If so how should I be doing this?

Rodo Abad
@rodoabad
Anyone taken a look at this yet - sinonjs/sinon#1247
Nicolas Almy
@almynic
hi how do I stub a express api with sinon? This is my code. I want to stub the routes. The tests should be unittests and not integrationtests
var express = require('express'),
router = express.Router(),
passport = require('passport'),
passport_conf = require('../settings/passport_configuration');

// Admin-restricted routes
router.get('/admin*', passport_conf.ensureAuthenticated, function(req,res){
if(req.user['user-role'] != 4)
return res.sendStatus(403);
res.sendfile('frontend/secure/admin.html')
});

// Shop-restricted routes
router.get('/shop*', passport_conf.ensureAuthenticated, function(req,res){
if(req.user['user-role'] < 3)
return res.sendStatus(403);
res.sendfile('frontend/secure/shop.html')
});

// Logout
router.get('/logout', function(req, res) {
req.logout();
req.session.destroy();
res.redirect('/');
});

module.exports = router;
Nicolas Almy
@almynic
can anyone help me?
Nicolas Almy
@almynic
Nobody?
Peter Simmons
@cabbiepete
@almynic You can make the final handler less anonymous and then test it with a stub req, and stub res.
// Shop-restricted routes
router.get('/shop*', passport_conf.ensureAuthenticated, function(req,res){
if(req.user['user-role'] < 3)
return res.sendStatus(403);
res.sendfile('frontend/secure/shop.html')
});
Becomes
router.get('/shop*', passport_conf.ensureAuthenticated, shop);

function shop(req,res){
if(req.user['user-role'] < 3)
return res.sendStatus(403);
res.sendfile('frontend/secure/shop.html')
}
module.exports.shop = shop;
Then you can test shop by itself.
Make sense?
bo.jiang
@shiningstone
Hi, All. I'm tring to use practicalmeteor:sinon stub an interface instantiated from ValidatedMethod(call(args, cb)), but got the complaining says - Error: call to eval() blocked by CSP, Is there anyone could help me? Thanks a lot!
bo.jiang
@shiningstone
@shiningstone Problem solved - My project includes the package browser-policy, which disables eval()
Elwyn
@elwynelwyn
Any advice on how to test this?
function underTest() {
myFoo.dispatch(new Widget());
}
let spy = sinon.spy(myFoo, 'dispatch');

underTest();

expect(spy).to.have.been.calledWithInstanceOf(Widget);
I can do it this way, but it seems messy:
expect(spy.firstCall.args[0]).to.be.an.instanceOf(Widget);
Craig Gardner
@cgardner
Is anybody successfully stubbing Angluar 4.x services with Sinon?
Elwyn
@elwynelwyn
@cgardner I am.
let myCoolService = TestBed.get(MyCoolService);
sinon.stub(myCoolService, 'doTheThing').returns(Observable.of(true));
pragmaproducts
@pragmaproducts

can anyone please help me with how I can test this, I am running in circles and would appreciate any help

function getFiles(query) {
return new Promise((resolve, reject) => {
const options = {
};

glob(query, options, (error, files) => {
if (error) {
console.error(error);
reject(error);
}

resolve(files);
});
});
}

I want to mock out glob and pass in values for the callback (error, files) so that I can check that it handles things correctly.
I have in the test a stub

        const globMock = sinon.stub().yields();
proxyquire('./../../src/lib/files', {
'glob': globMock
});

but i am not sure how to ensure that the callback of the glob defines the required parameters

Juliano Nunes
@julianonunes_twitter
Hi everyone. Is it possible to test my model based on Knex.js without writing to the DB or undoing the changes after each test (is it what the sandbox is all about?)?
Ben Claar
@claar
Sorry, it's my first time using sinon and I'm fairly lost
Ivan Etchart
@ivanetchart
Hi everyone! got a question...what about using global stubs ? Do you think it's a bad practice & how you will avoid it? thanks a lot
Samuel Joli
@Samueljoli
Hey Node world
I'm having some issues using sinon stubs and it may stem from how I'm implementing namespacing on the module that I'm looking to stub
//...my module.js
const Constructor = require('./constructor') //...just exports a singleton

// Need to namespace some of my functions and retain the this context
Object.defineProperty(Constructor.prototype, 'es', {
get: function() {
return {
method: require('./implementations/doesSomething.js').bind(this)
}
}
});

module.exports = Constructor;

//...testFile.js
const Constructor = require('./constructor');
const sinon = require('sinon');

sinon.stub(Constructor.es, 'method', function() {
return 'hijacked original method'
});

/*
...some test cases
Namespaced functions will not be stubbed, but functions not namespaced (directly defined on the prototype) are stubbed as I would expect
*/
Oleksandra Kalinina
@korel-san

Hi, all! I'm trying to test child process which runs nodejs file via spawn :

//  index.js
var spawn = require('child_process').spawn;
var proc = spawn('node', [cliPath], { stdio: [null, null, null] });
module.exports = { run: () => {
return new Promise(function(resolve, reject) {
const steps = [];
proc.stdout.on('data', function(line) {
steps.push(line);
})
proc.stdout.on('close', function() {
resolve(steps);
})
proc.stdout.on('error', reject);
});
}}

In the child process I make a request to some third party servers.
As far as I understand I could just only start my own stub server which will respond with data for certain test suits.
But I couldn't run it:

//  test.js
var  {run} = require('./index.js');
const sinon = require('sinon');
const Bluebird = require('bluebird');
const {HttpServer} = require('sinon-server');

"should authenticate user": async () => {
server
.withArgs(
'POST',
'/api/cli/authenticate',
{
'host': 'localhost:3000',
'accept-encoding': 'gzip, deflate',
'user-agent': 'node-superagent/3.5.2',
'content-type': 'application/x-www-form-urlencoded',
'x-cli-version': '2.6.13',
'content-length': '38',
'connection': 'close'
},
'email=test%test.org&password=qwerty'
)
//      .usingPromise(Bluebird.Promise);
.resolves({
status: 200,
headers: {'Content-Type': 'application/json'},
body: {'success': true, 'data': {'token': 'AAAAAAAAAAAAAAAAAaaaaaaaaaaaaaaaaaaAAAAAAAAAAAAAA'}}
});

await server.start()
.then(() => run(cliPath, keys))
.then((stdout) => {
const prettifiedSteps = prettifyStdout(stdout);
checkExpectedSteps(expectedSteps, prettifiedSteps);
});
}

I've tried many different solutions, but It doesn't help me.
Have you any idea how I could solve this issue? Or do you have any idea how it could be solved by another way?
PS. It's for e2e tests (interactive cli tool)

hannes
@escapedcat
anyone here could point me to an acrticle/post/info how to use tape with sinons fakeserver?
Jeremy Smith
@jeremy-smith-maco
Hey. I am trying to stub an ES6 constructor. I've read a lot of stuff about people not understanding constructors and what not but I need someway for the constructor of a class to not run.\
I am testing the constructor of one class which I want to run but I want to stub another Class's constructor that is called by the testing constructor.
I don't want it to run because it fails when I run the whole test suite.
Adrien Horgnies
@AdrienHorgnies
Anyone knows how to mock/stub functions from the same 'class' as the function under test ?
AFunction = () => { ; }
FunctionUnderTest = () => { AFunction(); }
Nishant Jain
@nishant-jain-94
Hi all, How to spy on functions available on global or window object.?
Adrien Horgnies
@AdrienHorgnies
@nishant-jain-94 Did you try something like sinon.spy(Window, 'myFunction')` ?