mardi 11 février 2020

I'm not able to test my sails.js controller with chai and sinon

I have a controller Acounts with a method sum, and a service file named validation with an object register. This object has a method validate that validates the form provided and returns a Boolean.

Controller

sum: function(req, res) {

    //validate form with a validation service function
    const validator = new validation.register();
    let check = validator.validate(req.body.form);

    let count = 0;

    if (check) {
        count += 1;
    } else {
        count -= 1;
    }

    res.send(count);

},

test

//imports
const chai = require("chai");
const expect = chai.expect;
const sinon = require("sinon");
const util = require('util'); // to print complex objects
const acountsC = require("../../../api/controllers/AcountsController.js");

describe("AcountsController", function()  {
  describe("sum", function() {

    let req = {
        body: {
            form: {}
        }
    }

    let res = {
        send: sinon.spy()
    }

    let validation = {
        register: {
            validate: function() {}
        }
    }       

    let stub_validate = sinon.stub(validation.register, "validate").returns(true);


    it("count should be 1 when validation is true", function() {

        acountsC.sum(req, res);

        expect(count).to.equal(1);

    });


  });
});

test log

AcountsController
    sum
      1) count should be 1 when validation is true


  0 passing (5s)
  1 failing

  1) AcountsController
       sum
         count should be 1 when validation is true:
     ReferenceError: count is not defined

note

I understand that the test is supposed to execute the piece of code we are calling, while replacing the external functions called in that piece of code(The controller) making it return whatever we set. If the test is executing that piece of code, why I can't access any variables created in the controller?

I've tried by spying res.send(), and check if it was called with a 1. I didn't succeed. I searched everywhere how to perform an assertion to a variable, but I found nothing. :(

hope you can help

Aucun commentaire:

Enregistrer un commentaire