by

Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Elwyn
    @elwynelwyn
    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') ?
    Nishant Jain
    @nishant-jain-94
    @AdrienHorgnies No I was using it in NodeJS
    Allen Houng
    @ayhoung
    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
    @AdrienHorgnies
    @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
    @ayhoung
    @AdrienHorgnies thanks for the feedback
    however, wouldn’t supplying the spy as an argument require a change in the core code?
    Adrien Horgnies
    @AdrienHorgnies

    @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
    @lvegerano

    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
    @AdrienHorgnies
    @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;'
    };
    objectkit
    @objectkit

    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?

    Thanks!

    Hekar Khani
    @hekar
    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
    @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 = {};
    
      sequence(context)
            .phase(next)
            .phase(next)
            .phase(next)
            .boot(done);
    
        t.truthy(done.calledOnce);
    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
    @james-gardner
    The answer is not to use spies or mocks.
    Stefan Schneider
    @hinogi
    good evening
    Brandon Istenes
    @brandones

    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
    @brandones
    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
    @AdrienHorgnies

    @brandones I advice you to always use the sandbox

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

    You can check some tests here

    Adrien Horgnies
    @AdrienHorgnies
    @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]
    true
    > spy.getCall(20).args[3] === spy.args[20][3]
    true
    Brandon Istenes
    @brandones
    Yeah, it turned out that the function I was expecting to be called was being called in a promise, and I wasn't waiting for the promise before running my assertions.
    Sandbox seems like just the thing. Perhaps it deserves a more prominent note in the documentation (e.g. in connection with stubbing out whole objects). Thank you for your help!
    Adrien Horgnies
    @AdrienHorgnies
    @brandones I have tons of tests with promises if you want, you can check some if you want.
    Adrien Horgnies
    @AdrienHorgnies
    And yes, I agree with you, sandbox should get more light. I had read the whole documentation plus a tutorial or two about sinon when sinon.sandbox didn't exist. When I discovered it existed by mistake, I thought that it would save me time, make code more readable and more importantly, that would save collaborators from forgeting to verify or restore spies & co.
    Brandon Istenes
    @brandones
    @AdrienHorgnies Nice, thanks!
    Brandon Istenes
    @brandones

    Okay, new problem.

    foo.js

    const doFoo = () => { console.log('bad stuff!') }
    const doBar = () => { doFoo() }
    module.exports = { doFoo, doBar }

    foo.test.js

    const sandbox = require('sinon').sandbox.create()
    const foo = require('./foo')
    
    describe('doBar', () => {
      before(() => {
        sandbox.stub(foo, 'doFoo')
      })
      it('should call doFoo', () => {
        foo.doBar()  // prints "doFoo" to console
      })
    })

    What gives? Why isn't doFoo mocked when doBar calls it?

    Adrien Horgnies
    @AdrienHorgnies
    @brandones If I remember well, you can only wrap functions external to the code you test.
    In your test suit, you're calling a function and mocking another from the same module. That won't work; my guess is that it is because both functions are defined at the same time, giving no opportunity to sinon to wrap doFoo before doBar is defined.
    Anyway, if you must mock functions from the unit you're testing, it smells bad. Either you should move doFoo to another module or you should target more precisely the dangerous section : sandbox.stub(console, 'log');.
    Dimitris Karagiannis
    @mkarajohn
    Hello! I'd like to ask, is it possible to execute a callback once a spy has been called ?