Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
    thank you
    Amal Hussein
    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
    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

    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 {
    // test.spec.js
    import * as all from 'try-sinon';
    stub(all, 'foo').returns(1000); // This stub works: === 1000
    stub(all, 'bar').returns(1001); // No luck: === 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
    @burnall Can you show code generated by babel?
    Maxim Fainberg
    @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

    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
    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
    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
    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.

    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]);

    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
    Anyone taken a look at this yet - sinonjs/sinon#1247
    Nicolas Almy
    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);
    // Shop-restricted routes
    router.get('/shop*', passport_conf.ensureAuthenticated, function(req,res){
        if(req.user['user-role'] < 3)
            return res.sendStatus(403);
    // Logout
    router.get('/logout', function(req, res) {
    module.exports = router;
    Nicolas Almy
    can anyone help me?
    Nicolas Almy
    Peter Simmons
    @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);
    router.get('/shop*', passport_conf.ensureAuthenticated, shop);
    function shop(req,res){
        if(req.user['user-role'] < 3)
            return res.sendStatus(403);
    } = shop;
    Then you can test shop by itself.
    Make sense?
    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!
    @shiningstone Problem solved - My project includes the package browser-policy, which disables eval()
    Any advice on how to test this?
    function underTest() {
        myFoo.dispatch(new Widget());
    let spy = sinon.spy(myFoo, 'dispatch');
    I can do it this way, but it seems messy:
    Craig Gardner
    Is anybody successfully stubbing Angluar 4.x services with Sinon?
    @cgardner I am.
    let myCoolService = TestBed.get(MyCoolService);
    sinon.stub(myCoolService, 'doTheThing').returns(Observable.of(true));

    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) {

    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
    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
    Sorry, it's my first time using sinon and I'm fairly lost
    Ivan Etchart
    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
    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
    // 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;
    const Constructor = require('./constructor');
    const sinon = require('sinon');
    sinon.stub(, '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

    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) {
        proc.stdout.on('close', function() {
        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 () => {
              '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'
    //      .usingPromise(Bluebird.Promise);
            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)

    anyone here could point me to an acrticle/post/info how to use tape with sinons fakeserver?
    Jeremy Smith
    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
    Anyone knows how to mock/stub functions from the same 'class' as the function under test ?
    AFunction = () => { ; }
    FunctionUnderTest = () => { AFunction(); }
    Nishant Jain
    Hi all, How to spy on functions available on global or window object.?
    Adrien Horgnies
    @nishant-jain-94 Did you try something like sinon.spy(Window, 'myFunction') ?
    Nishant Jain
    @AdrienHorgnies No I was using it in NodeJS
    Allen Houng
    hi all
    i was wondering how to get this inside of a fakeCall?
    const stub = sinon.stub(Person.prototype, ’sayHello').callsFake(() => {
        console.log(this); //returns empty object
        return Promise.resolve({});
    this just returns an empty object
    Adrien Horgnies
    @ayhoung You can assert the context this with sinon method spy.calledOn(obj);. This compares the parameter obj you provide to the test with the actual this used to call the method.
    I suppose you can replace the anonymous function with a spy as the argument of the callsFake method.
    Allen Houng
    @AdrienHorgnies thanks for the feedback