Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Ifemide
    @bwoodlt
    I'm trying to understand sinonjs usage.. read the documentation
    I have a function that gets a product from db, whats best to use? stub, spies or mock? and assuming I do const callback = spy.stub(exampleFn()), then does that mean the callback will be able to do the job of my exampleFn?
    Alexander Escamilla
    @alexesca
    How can I stub a middleware in nodejs?
    ƇʘƁ̆ąƇ́
    @anchnk
    function wrapTypeError(typeError) {
      const errData = {data: {event: 'TypeError'}};
      return Object.assign(typeError, errData);
    }
    
    function wrapGotError(gotError) {
      const apiClientError = apiClientErrorsFactory(gotError);
      const error = { data: {}};
      try {
        Object.assign(error.data, apiClientError);
        return error;
      } catch (typeError) {
        return wrapTypeError(typeError);
      }
    }
    Hey I am trying to cover the case where the second Object.assign statement throws an error
    So I would like to override the behavior of Object.assign only when it's called with error.data and apiClientError so that it throws a TypeError
    I am struggling to do so (btw I am using mocha to run my unit tests), any of you have an ideas on how to handle that ?
    Christopher Hill
    @christopherhill
    Does anyone have experience integrating Sinon with Knex? I'm having a tough go of it. I created a gist here: https://gist.github.com/christopherhill/33363c8c980fce83a6617e91d4c18e39. If anyone can help I'd really appreciate it.
    Andrew Koroluk
    @Awk34
    hey guys
    first, I was curious about how sinon had changed from 1.0.0 to latest, but the http://legacy.sinonjs.org/ site is down
    2nd, it looks like 5.0.0 was released on npm but not pushed to GitHub :]
    Phil Gold
    @pgoldrbx
    Also trying to understand the 5.0.0 release. Wondering if it was accidental? I just got about 50 greenkeeper PRs. However, I don't see a release commit on the next branch, and dist tags have not changed either: $ npm view sinon dist-tags =>
    { latest: '4.4.8', next: '5.0.0-next.3' }
    As far as I can tell, this appears to have been accidental, and I'm going to ignore it.
    Phil Gold
    @pgoldrbx
    Looks like it happened again today? Does anyone monitor this channel? I guess I can open an issue on the repo
    This could also be a bug in Renovate app being persistent
    Tobias
    @totokaka

    Any people around here?
    I need some help with using mocks. I want to mock a WebSocket to verify that my class registers a listener, but it seems sinon let's the original method execute? I was able to reproduce this in a simple test also:

    class Thing {saySomething() { console.log("Something!");}}
    const t = Object.create(Thing.prototype);
    const mock = sinon.mock(t);
    t.saySomething();

    This actually logs 'Something!' to the console, I was under the impression that it shouldn't?

    However, if I set expectations for the method, it is properly stubbed. Is there any way to stub all methods of the object?
    Dean Sofer
    @ProLoser
    I'm upgrading from 1.x to 5.x and the documentation is a little inconsistent
    am I not supposed to create a sandbox anymore?
    The docs say sandbox = sinon.sandbox for default, but it also says sinon is the default sandbox
    Mike Hingley
    @computamike

    Hi - I have a question about stubbing / doubling complex objects. I'm trying to mock an adonis model object - so here's the code I'm looking to test :

      async index ({ request, session, view, response, params }) {
        const messages = await Messages.query().has('messagedeliveryrecordsMessageId').with('messagedeliveryrecordsMessageId').fetch()
        const messagesJson = messages.toJSON()
        return view.render('messages/index', { title: 'Message Processing', messages: messagesJson })
      }

    at the moment I'm trying to create a mock of the message.query line :

    const messages = await Messages.query().has('messagedeliveryrecordsMessageId').with('messagedeliveryrecordsMessageId').fetch()

    I have a basic test like this - which works (as far as this line is concerned)

    it.only('MessageController calls Messages.Query - returns null', async () => {
    
         const messagesStub = sinon.stub()
        messagesStub.toJSON = sinon.stub().returns('validJson')
        const fetchstub = sinon.stub().returns(messagesStub)
        const withstub = sinon.stub().returns({fetch: fetchstub})
        const hasstub = sinon.stub().returns({with: withstub})
        const mockMessages = sinon.createStubInstance(Messages)
        mockMessages.query = sinon.stub().returns({has: hasstub})
        mockMessages.toJSON = sinon.stub().returns('valid json here')
    
    
    
        const SUT = new MessageController(mockMessages)
        // Act
        let result = await SUT.index({request:null})
        // Assert
    
      })

    I plan on adding some asserts - like for instance asserting that the has stub was called with 'messagedeliveryrecordsMessageId' parameter.

    My question is : All of the stub set up i'm doing in the test seems messy and not great. Is there a nicer way I can format this?

    Mike Hingley
    @computamike
    I think I have a nicer format - Will post it up shortly
    This might be nicer -
      it.only('MessageController calls Messages.Query - returns null', async () => {
        const mockMessages = {
          query: sinon.stub().returns({
            has: sinon.stub().returns({
              with: sinon.stub().returns({
                fetch: sinon.stub().returns({
                  toJSON: sinon.stub().returns('validJSON')
                })
              })
            })
          })
        }
    
        const SUT = new MessageController(mockMessages)
        // Act
        let result = await SUT.index({request: null, view: {render: sinon.stub()}})
        // Assert
        expect(mockMessages.query.calledOnce).to.equal(true)
        expect(mockMessages.query().has.calledOnce).to.equal(true)
        expect(mockMessages.query().has.getCall(0).args[0]).to.equal('messagedeliveryrecordsMessageId')
        expect(mockMessages.query().has().with.calledOnce).to.equal(true)
        expect(mockMessages.query().has().with.getCall(0).args[0]).to.equal('messagedeliveryrecordsMessageId')
      })
    what do you think? I think it's a bit nicer in terms of nesting
    I'd like to know how to test my component's state after the setState is invoked
    (after my async function)
    jjkim325
    @jjkim325
    Is this the correct place to ask usage questions?
    Dinoloop
    @ParallelTask
    Hi Guys!
    Dinoloop is a Rest API framework for Nodejs powered by Typescript with Dependency Injection.
    Please find the project wiki https://github.com/ParallelTask/dinoloop/tree/master/wiki and please let me know your valuable thoughts on my self project. I would like to hear advice's from community.
    Dinoloop
    @ParallelTask

    the design goal of dinoloop project is to make C#/Java programmers to easily switch to Nodejs with less learning curve
    .

    dinoloop provides MVC architectural changes with controllers, services and constructor dependency injection,
    SOLID principles are great with OOPS and that is what dinoloop added to typescript using inverifyjs (DI container)
    .

    dinoloop provides bare minimum architecture, you are still free to use all your express objects
    .
    the way express does not abstract you from node, similarly dinoloop does not abstract you from express.

    So adding dinoloop does not harm you anywhere in your project, you can give it a try

    https://github.com/ParallelTask/dinoloop

    Quickstart
    Step 1: Create package.json

    {
    "name": "dinoloop-starter",
    "version": "1.0.0",
    "scripts": {
    "build": "rimraf dist && tsc --p ./tsconfig.json",
    "start": "npm run build && node dist/app.js"
    },
    "dependencies": {
    "dinoloop": "^1.0.0",
    "express": "^4.16.3"
    },
    "devDependencies": {
    "@types/express": "^4.11.1",
    "@types/node": "^7.0.22",
    "rimraf": "^2.5.2",
    "typescript": "~2.4.2"
    }
    }
    Step 2: Create home.controller.ts

    import { ApiController, Controller, HttpGet } from 'dinoloop';

    @Controller('/home')
    export class HomeController extends ApiController {

    @HttpGet('/get')
    get(): string {
        return 'Hello World!';
    }

    }
    Step 3: Create app.ts

    import express = require('express');
    import bodyParser = require('body-parser');
    import { Dino } from 'dinoloop';
    import { HomeController } from './controllers/home.controller';

    const app = express();

    // Dino requires express app instance
    // and the base-uri on which dino app to be mounted
    let dino = new Dino(app, '/api');

    // Dino requires express router
    dino.useRouter(() => express.Router());
    dino.registerController(HomeController);

    // Binds the dino instance to express
    dino.bind();

    // Start the express server
    app.listen(8088, () => console.log('Server started on port 8088'));
    Run the following npm commands

    npm install - to install dependencies.
    npm start - to start the express app.
    Navigate to http:localhost:8088/api/home/get in browser and you will see the response

    For complete details, please refer https://github.com/ParallelTask/dinoloop-starter and https://github.com/ParallelTask/dinoloop.

    William Lightning
    @fuel-wlightning
    Is there a way to do something like sinon.stub().callsArgWith(1, {}) the return of the stub is what is returned by the called arg?
    William Lightning
    @fuel-wlightning
    ended up instead of using stub, wrapping a small function in a spy.
    Robert Main
    @robertmain
    Hey folks
    Scott Stern
    @sstern6

    Question, when you have a constructor.

    const Test = function() {
      this.testFunc = function () {}
    }
    `

    I have been trying to stub this.testFunc by sinon.stub(Test.prototype, 'testFunc').returns([]);

    But this isnt working, any ideas?

    i see in the docs there are sinon.createStubInstance but i was trying to just use sinon.stub
    Brad Compton (he/him)
    @Bradcomp
    You can instantiate an Object and stub out the method:
    const test = new Test();
    sinon.stub(test, "testFunc")
    Otherwise createStubbedInstance(Test, {testFunc: sinon.stub().returns([])})
    Scott Stern
    @sstern6
    ok perfect
    thank you
    wasnt sure if stubbing the instance was a bad idea
    thanks!
    Phred
    @fearphage

    This might be nicer -

      it.only('MessageController calls Messages.Query - returns null', async () => {
        const mockMessages = {
          query: sinon.stub().returns({
            has: sinon.stub().returns({
              with: sinon.stub().returns({
                fetch: sinon.stub().returns({
                  toJSON: sinon.stub().returns('validJSON')
                })
              })
            })
          })
        }
        const SUT = new MessageController(mockMessages)
        // Act
        let result = await SUT.index({request: null, view: {render: sinon.stub()}})
        // Assert
        expect(mockMessages.query.calledOnce).to.equal(true)
        expect(mockMessages.query().has.calledOnce).to.equal(true)
        expect(mockMessages.query().has.getCall(0).args[0]).to.equal('messagedeliveryrecordsMessageId')
        expect(mockMessages.query().has().with.calledOnce).to.equal(true)
        expect(mockMessages.query().has().with.getCall(0).args[0]).to.equal('messagedeliveryrecordsMessageId')

    This syntax in the assertions is too complex for my taste. I would make the setup more complex, but the tests would be simplified.

    beforeEach(function() {
      this.toJSONStub = sinon.stub();
      this.fetchStub = sinon.stub().returns(this.toJSONStub);
      this.withStub = sinon.stub().returns(this.fetchStub);
      ...
      this.queryStub = sinon.stub().returns(this.hasStub);
      this.mockMessages = { query:  this.queryStub };
    });
    
    it('should do a thing', function() {
      triggerTestCase(this.mockMessages);
    
      // which simplifies the assertions
      assert.calledOnce(this.queryStub);
      ...
      assert.calledOnce(this.toJSONStub);
    });
    Clite Tailor
    @clitetailor
    How Sinon homepage was generated? Is there any tool because i love the homepage style and really want to make a variant of it on my own repo! :/
    Clite Tailor
    @clitetailor
    Okey, i found it. Sinon is great!
    Nephtali Rodriguez
    @nrodriguez
    Hi All. I'm attempting to use calledWithMatch but it seems that still only does a fuzzy compare. Is there any way I can do an exact object to object comparison so that if the value of one of the keys is different it returns false?
    Joakim Bajoul Kakaei
    @Todai88
    Is this community still active?
    Lars Gyrup Brink Nielsen
    @LayZeeDK
    Not very much.
    Sasha Boginsky
    @sashadev-sky
    hey! Does anyone here have experience writing tests in sinon with Ruby on Rails and could help me with some questions I have
    Richard Annand
    @rj175
    Not sure if this channel is still active but I am looking for some help with the sinon.stub method
    Derek W. S. Gray
    @derekwsgray
    @rj175 what's the question?