Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
    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);
    module.exports.shop = 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
    //...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;
    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

    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
    however, wouldn’t supplying the spy as an argument require a change in the core code?
    Adrien Horgnies

    @ayhoung No, use a stub to create whatever behavior you need, knowing that a stub has spies full functionalities.

    They [stubs] support the full test spy API in addition to methods which can be used to alter the stub’s behavior.

    Luis Vegerano

    Hi all, I have an object

    const contextAPI = {
      auth: {
        lock_api_call() { return true; },
      sql: 'SELECT * FROM foo;',

    that I would like to mock const context = Sinon.mock(contextAPI);
    but I’m getting an error Attempted to wrap undefined property lock_api_call as function and Im not sure what am I doing wrong. Any pointer would be appreciated

    Adrien Horgnies
    @lvegerano I don't quite understand the usefulness of sinon.mock but I can say it works better when you mock things such as const lib = require('libYouWantToMock');
    If it's an object you provide as a parameter to the unit you're testing, just build whatever you want to replace the actual parameter (and possibly put a spy/stub whatever function there is in your function).
    const lockStub = sinon.stub().returns(true);
    const contextAPIDummy = {
        auth: {
            lock_api_call : lockStub
        sql: 'SELECT * FROM foo;'

    Hi there - glad to find this room! Just a quick one to start - I’m installing sinon latest via npm like so:

    npm i -D sinon

    when I do

    npm list sinon

    sinon is reported as version 2.4.1, yet the latest release is3.2.1 apparently…

    Any idea why there is a version difference?


    Hekar Khani
    Hello, could a patch version (3.3.1) be published to npm with #1563?
    jxLoaderdoesn't have a license (among other issues. ie. not sure we want such questionable dependencies executing during our builds.)
    James Gardner
    Hi, I'm struggling with writing a test at the moment. I'm basically trying to test a sequence that runs error first callbacks. What I'd like to be able to do is check that an objects been modified within each call:
       const next = (ctx, next) => next();
      const done = sinon.spy();
      const context = {};
    so for each phase context has a property bolted on to it
    I'd love to be able to use something like:
        const phase = sinon.stub().callArg(1);
            phase.onCall(0) ....
    But how can I modify context from the stub ?
    James Gardner
    The answer is not to use spies or mocks.
    Stefan Schneider
    good evening
    Brandon Istenes

    Hey folks, I'm mocking out a whole object (against the advice of the docs) like

    myStub = sinon.stub(myObj)

    However, that doesn't seem to define a restore method on myStub. How do I restore the original object?

    Brandon Istenes
    Oh wow, I just found out that where the documentation says, e.g. spy.args, it actually means call.args, where call is the sort of object returned by spy.getCall(0).
    Even if for some strange reason args is in fact defined on spies themselves (which it seems to be), the documentation seems misleading with respect to actual usage.
    Adrien Horgnies

    @brandones I advice you to always use the sandbox

    const sandbox = sinon.sandbox.create();
    // do things

    You can check some tests here

    Adrien Horgnies
    @brandones Regarding args, I didn't find the documentation confusing : Array of arguments received, spy.args[0] is an array of arguments received in the first call..
    But as you do seem confused, maybe some code can help you :
    > spy.thirdCall.args === spy.args[2]
    > spy.getCall(20).args[3] === spy.args[20][3]