Search code examples
javascriptnode.jssinonchaisupertest

Stubing a class call from another function


I have 2 files controller.js and entity.js which interact with each other. I am testing controller.js, and it creates an instance of entity.js (class) and use one of its functions. How can I stub/mock/spy the call and the return of that method?

controller.js

const controller= async (req, res) => {

try {
    ...

    const entity = new Entity({
    ...
    });

    const validation = await entity.validate();

    ...
    return res.send()
    }
  } catch (error) {
    return res.send(error)
  }
};

Entity.js

class Entity{
  constructor() {
  ...
  }

  ...

  async validate() {
    ...
    return response;
  }
}

Any idea how to test controller.js using supertest, sinon and chai?


Solution

  • Sinon will happily stub the function. Since it's a class method you just need to be sure to stub the function on the prototype:

    const controller = async (req, res) => {
          const entity = new Entity();
          const validation = await entity.validate();
          console.log(validation)
      };
      
    class Entity{
        constructor() {}
        async validate() {
          return "real function";
        }
    }
    // stub it
    let stub = sinon.stub(Entity.prototype, 'validate')
    stub.returns('stubbed function')
    
    controller()
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/7.1.1/sinon.min.js"></script>