Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
    Andrew Vaughan
    They use "this" inside an object that isn't a class
    I've tried stubbing the response calls, I've tried to call it with .call and .apply to set what this should be, and a number of other things, but this is always {} inside the intent object
    Any idea how I might be able to mock or stub the properties that the object is calling on this inside that object so I can test if they're called?
    For the lazy who don't want to go to the link, here's an example of what I'm talking about
    const handlers = {
        'HelloWorldIntent' : function() {
            //emit response directly
            this.emit(':tell', 'Hello World!');
    Andrew Vaughan
    Unfortunately, trying to mock emit in this example throws TypeError: Attempted to wrap undefined property emit as function - since they don't build a proper class
    Andrew Vaughan
    Or spy, rather
    Andrew Vaughan
    Resolved it myself - kindof - for those interested, I couldn't call apply because I was using arrow functions in my module
    If I revert them to old-school anonymous functions, it overrides this as planned - gotta do some reading as to why the arrows weren't working
    Alexander Escamilla
    // Import qbs
    import {getQbo} from "./../../utils/quickBooks/qbo.module";
    // My new instance 
    const invoiceModule: InvoiceModule = new InvoiceModule(getQbo);
    // My class 
    export class InvoiceModule {
        qbo: any;
        addressModule: AddressModule = new AddressModule();
        customerModule: CustomerModule = new CustomerModule();
        emailModule: EmailModule = new EmailModule();
        constructor(getQbo) {
            const token = process.env.QB_APP_TOKEN;
            const companyId = process.env.QB_COMPANY_ID;
            const refresh = process.env.QB_APP_TOKEN_REFRESH;
            this.qbo = getQbo(token, companyId, refresh);
    @jeffhall-wk sorry for the wait. Hope it helps
    @alexesca thanks!
    Alexander Escamilla
    I use nodeJS, typescript, sinonTest, and rxjs-marble in my project. I am trying to stub my funcitons, but sinon does not mock all of them. How can I use sinon and marbles at the same time?
    before(marbles(function(m) {
            composeInvoiceEmailHtmlMock = sinon.stub(InvoiceModule.prototype,'composeInvoiceEmailHtml')
             .returns('<p>It was mocked</p>');*/
            composeCustomerMock$ = sinon.stub(InvoiceModule.prototype, 'composeCustomerAndCreateCustomerInQBO')
                .returns(m.cold('--a|', {a: customerMock}));
            composeInvoiceMock$ = sinon.stub(InvoiceModule.prototype, 'composeInvoiceAndCreateInvoiceInQBO')
                .returns(m.cold('--a|', {a: invoiceMock}));
            sendEmailMock$ = sinon.stub(InvoiceModule.prototype, 'sendEmail$')
                .returns(m.cold('--a|', {a: 'SENT_EMAIL'}));
        after(function () {
        it('should create an invoice in QBO', marbles(function(m) {
                const b = m.cold('------b', {b: 'SENT_EMAIL'});
    I wanna be able to use sinonTest
    it('should do something with stubs', sinon.test(function() {
      var stub = this.stub($, 'post');
    Alexander Escamilla
    If you guys ever need to test observables with marbles and sinon, this is how i did it,
    var sinon = require('sinon');
    let sinonTestFactory = require("sinon-test");
    let sinonTest = sinonTestFactory(sinon);
    it('should test the createECHeckCharge function', sinonTest(function() {
            const that = this;
            marbles(m => {
                that.stub(request, 'post').yields(null, {OK: true}, {status: 'CAPTURED'});
                m.expect(paymentModule.createCharge({})).toBeObservable(m.cold('a', {a: {status: 'CAPTURED'}}))
    Remco Gubbels
    I'm currently trying to rewrite a piece of codebase from callbacks to promises, but sadly the tests are now failing due to the callFake method isn't being picked up, anyone experienced something like that before?
    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
    How can I stub a middleware in nodejs?
    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
    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
    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
    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
    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

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

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

    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
    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
    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)
    Is this the correct place to ask usage questions?
    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.

    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


    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';

    export class HomeController extends ApiController {

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

    // Binds the dino instance to express

    // 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
    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
    ended up instead of using stub, wrapping a small function in a spy.
    Robert Main
    Hey folks