Sinon stub is being ignored outside of the test fileWriting files in Node.jsWhat's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?Sinon - stubbing function with callback - causing test method to timeoutStub a closure function using sinon for redux actionsWhen testing an ExpressJS route using mocha+sinon, how do you “stub” a function that's local to the route?No logs after Passport.js authenticate middlewareNodeJS, passport-jwt: Authenticate all user except in listTesting that function is called with parameter in a PromiseJWT token issue and passport w/ node jsSinon doesn't stub my intern fuctions while testing. (ExpressJS)

How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?

Is this a crack on the carbon frame?

Which models of the Boeing 737 are still in production?

What are these boxed doors outside store fronts in New York?

What is the word for reserving something for yourself before others do?

Why, historically, did Gödel think CH was false?

Finding angle with pure Geometry.

Why was the small council so happy for Tyrion to become the Master of Coin?

How does strength of boric acid solution increase in presence of salicylic acid?

Modeling an IPv4 Address

Why are electrically insulating heatsinks so rare? Is it just cost?

Test if tikzmark exists on same page

"You are your self first supporter", a more proper way to say it

In Japanese, what’s the difference between “Tonari ni” (となりに) and “Tsugi” (つぎ)? When would you use one over the other?

Is it possible to do 50 km distance without any previous training?

Can divisibility rules for digits be generalized to sum of digits

To string or not to string

Mage Armor with Defense fighting style (for Adventurers League bladeslinger)

What are the differences between the usage of 'it' and 'they'?

Theorems that impeded progress

Arthur Somervell: 1000 Exercises - Meaning of this notation

Font hinting is lost in Chrome-like browsers (for some languages )

Have astronauts in space suits ever taken selfies? If so, how?

How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?



Sinon stub is being ignored outside of the test file


Writing files in Node.jsWhat's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?Sinon - stubbing function with callback - causing test method to timeoutStub a closure function using sinon for redux actionsWhen testing an ExpressJS route using mocha+sinon, how do you “stub” a function that's local to the route?No logs after Passport.js authenticate middlewareNodeJS, passport-jwt: Authenticate all user except in listTesting that function is called with parameter in a PromiseJWT token issue and passport w/ node jsSinon doesn't stub my intern fuctions while testing. (ExpressJS)






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















I'm using mocha, chai, and sinon to test some authenticated API routes. I'm using passport.authenticate() as middleware to authenticate the route:



const router = require('express').Router();
const passport = require('passport');

router.post('/route',
passport.authenticate('jwt', session:false),
function(req,res)
return res.status(200);
);
module.exports = router;


Then, in my test suite, I am using sinon to stub out passport.authenticate calls:



const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
const passport = require('passport');
const server = require('../../app');
const expect = chai.expect;

chai.use(chaiHttp);
describe('route', function()
before(function(done)
sinon.stub(passport, 'authenticate').callsFake(function(test, args)
console.log('Auth stub');
);
console.log('stub registered');
passport.authenticate('jwt', session:false);
done();
);
after(function(done)
console.log('after hook');
passport.authenticate.restore();
done();
);
describe('POST /route', function()
it('should post', function(done)
console.log('starting test');
chai.request(server)
.post('/route')
.end(function(err,res)
expect(res).to.have.status(200);
done();
);
);
);
);


Now, when I run the test suite, I see it print out the following:



 route
stub registered
Auth stub
POST /route
starting test
1) should post
after hook

1 failing

1) route
POST /route
should post:

Uncaught AssertionError: expected Object (_events, _eventsCount, ...) to have status code 200 but got 401


From this, we can see that the after the stub is registered, I can call it in the test file and it is properly stubbed. But when passport.authenticate() is called in route.post(), it is the actual passport.authenticate() and sends a response with status 401 because I'm not authenticated.



Any thoughts on what's going on?










share|improve this question




























    2















    I'm using mocha, chai, and sinon to test some authenticated API routes. I'm using passport.authenticate() as middleware to authenticate the route:



    const router = require('express').Router();
    const passport = require('passport');

    router.post('/route',
    passport.authenticate('jwt', session:false),
    function(req,res)
    return res.status(200);
    );
    module.exports = router;


    Then, in my test suite, I am using sinon to stub out passport.authenticate calls:



    const chai = require('chai');
    const chaiHttp = require('chai-http');
    const sinon = require('sinon');
    const passport = require('passport');
    const server = require('../../app');
    const expect = chai.expect;

    chai.use(chaiHttp);
    describe('route', function()
    before(function(done)
    sinon.stub(passport, 'authenticate').callsFake(function(test, args)
    console.log('Auth stub');
    );
    console.log('stub registered');
    passport.authenticate('jwt', session:false);
    done();
    );
    after(function(done)
    console.log('after hook');
    passport.authenticate.restore();
    done();
    );
    describe('POST /route', function()
    it('should post', function(done)
    console.log('starting test');
    chai.request(server)
    .post('/route')
    .end(function(err,res)
    expect(res).to.have.status(200);
    done();
    );
    );
    );
    );


    Now, when I run the test suite, I see it print out the following:



     route
    stub registered
    Auth stub
    POST /route
    starting test
    1) should post
    after hook

    1 failing

    1) route
    POST /route
    should post:

    Uncaught AssertionError: expected Object (_events, _eventsCount, ...) to have status code 200 but got 401


    From this, we can see that the after the stub is registered, I can call it in the test file and it is properly stubbed. But when passport.authenticate() is called in route.post(), it is the actual passport.authenticate() and sends a response with status 401 because I'm not authenticated.



    Any thoughts on what's going on?










    share|improve this question
























      2












      2








      2








      I'm using mocha, chai, and sinon to test some authenticated API routes. I'm using passport.authenticate() as middleware to authenticate the route:



      const router = require('express').Router();
      const passport = require('passport');

      router.post('/route',
      passport.authenticate('jwt', session:false),
      function(req,res)
      return res.status(200);
      );
      module.exports = router;


      Then, in my test suite, I am using sinon to stub out passport.authenticate calls:



      const chai = require('chai');
      const chaiHttp = require('chai-http');
      const sinon = require('sinon');
      const passport = require('passport');
      const server = require('../../app');
      const expect = chai.expect;

      chai.use(chaiHttp);
      describe('route', function()
      before(function(done)
      sinon.stub(passport, 'authenticate').callsFake(function(test, args)
      console.log('Auth stub');
      );
      console.log('stub registered');
      passport.authenticate('jwt', session:false);
      done();
      );
      after(function(done)
      console.log('after hook');
      passport.authenticate.restore();
      done();
      );
      describe('POST /route', function()
      it('should post', function(done)
      console.log('starting test');
      chai.request(server)
      .post('/route')
      .end(function(err,res)
      expect(res).to.have.status(200);
      done();
      );
      );
      );
      );


      Now, when I run the test suite, I see it print out the following:



       route
      stub registered
      Auth stub
      POST /route
      starting test
      1) should post
      after hook

      1 failing

      1) route
      POST /route
      should post:

      Uncaught AssertionError: expected Object (_events, _eventsCount, ...) to have status code 200 but got 401


      From this, we can see that the after the stub is registered, I can call it in the test file and it is properly stubbed. But when passport.authenticate() is called in route.post(), it is the actual passport.authenticate() and sends a response with status 401 because I'm not authenticated.



      Any thoughts on what's going on?










      share|improve this question














      I'm using mocha, chai, and sinon to test some authenticated API routes. I'm using passport.authenticate() as middleware to authenticate the route:



      const router = require('express').Router();
      const passport = require('passport');

      router.post('/route',
      passport.authenticate('jwt', session:false),
      function(req,res)
      return res.status(200);
      );
      module.exports = router;


      Then, in my test suite, I am using sinon to stub out passport.authenticate calls:



      const chai = require('chai');
      const chaiHttp = require('chai-http');
      const sinon = require('sinon');
      const passport = require('passport');
      const server = require('../../app');
      const expect = chai.expect;

      chai.use(chaiHttp);
      describe('route', function()
      before(function(done)
      sinon.stub(passport, 'authenticate').callsFake(function(test, args)
      console.log('Auth stub');
      );
      console.log('stub registered');
      passport.authenticate('jwt', session:false);
      done();
      );
      after(function(done)
      console.log('after hook');
      passport.authenticate.restore();
      done();
      );
      describe('POST /route', function()
      it('should post', function(done)
      console.log('starting test');
      chai.request(server)
      .post('/route')
      .end(function(err,res)
      expect(res).to.have.status(200);
      done();
      );
      );
      );
      );


      Now, when I run the test suite, I see it print out the following:



       route
      stub registered
      Auth stub
      POST /route
      starting test
      1) should post
      after hook

      1 failing

      1) route
      POST /route
      should post:

      Uncaught AssertionError: expected Object (_events, _eventsCount, ...) to have status code 200 but got 401


      From this, we can see that the after the stub is registered, I can call it in the test file and it is properly stubbed. But when passport.authenticate() is called in route.post(), it is the actual passport.authenticate() and sends a response with status 401 because I'm not authenticated.



      Any thoughts on what's going on?







      node.js express mocha passport.js sinon






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 4:09









      dbarton91dbarton91

      4815




      4815






















          1 Answer
          1






          active

          oldest

          votes


















          0
















          Your code calls passport.authenticate as soon as it runs, and it runs as soon as it is required.



          Because you are requiring the code at the beginning of the test before the stub has been created your code ends up calling the real passport.authenticate.



          In order for code like this to call the stub you must set up your stub before you require your code:



          const chai = require('chai');
          const chaiHttp = require('chai-http');
          const sinon = require('sinon');
          const passport = require('passport');
          // const server = require('../../app'); <= don't require your code here...
          const expect = chai.expect;

          chai.use(chaiHttp);
          describe('route', function ()
          before(function (done)
          sinon.stub(passport, 'authenticate').callsFake(function (test, args)
          console.log('Auth stub');
          );
          console.log('stub registered');
          passport.authenticate('jwt', session: false );
          done();
          );
          after(function (done)
          console.log('after hook');
          passport.authenticate.restore();
          done();
          );
          describe('POST /route', function ()
          it('should post', function (done)
          console.log('starting test');
          const server = require('../../app'); // <= require it AFTER creating the stub
          chai.request(server)
          .post('/route')
          .end(function (err, res)
          expect(res).to.have.status(200);
          done();
          );
          );
          );
          );





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55056593%2fsinon-stub-is-being-ignored-outside-of-the-test-file%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0
















            Your code calls passport.authenticate as soon as it runs, and it runs as soon as it is required.



            Because you are requiring the code at the beginning of the test before the stub has been created your code ends up calling the real passport.authenticate.



            In order for code like this to call the stub you must set up your stub before you require your code:



            const chai = require('chai');
            const chaiHttp = require('chai-http');
            const sinon = require('sinon');
            const passport = require('passport');
            // const server = require('../../app'); <= don't require your code here...
            const expect = chai.expect;

            chai.use(chaiHttp);
            describe('route', function ()
            before(function (done)
            sinon.stub(passport, 'authenticate').callsFake(function (test, args)
            console.log('Auth stub');
            );
            console.log('stub registered');
            passport.authenticate('jwt', session: false );
            done();
            );
            after(function (done)
            console.log('after hook');
            passport.authenticate.restore();
            done();
            );
            describe('POST /route', function ()
            it('should post', function (done)
            console.log('starting test');
            const server = require('../../app'); // <= require it AFTER creating the stub
            chai.request(server)
            .post('/route')
            .end(function (err, res)
            expect(res).to.have.status(200);
            done();
            );
            );
            );
            );





            share|improve this answer



























              0
















              Your code calls passport.authenticate as soon as it runs, and it runs as soon as it is required.



              Because you are requiring the code at the beginning of the test before the stub has been created your code ends up calling the real passport.authenticate.



              In order for code like this to call the stub you must set up your stub before you require your code:



              const chai = require('chai');
              const chaiHttp = require('chai-http');
              const sinon = require('sinon');
              const passport = require('passport');
              // const server = require('../../app'); <= don't require your code here...
              const expect = chai.expect;

              chai.use(chaiHttp);
              describe('route', function ()
              before(function (done)
              sinon.stub(passport, 'authenticate').callsFake(function (test, args)
              console.log('Auth stub');
              );
              console.log('stub registered');
              passport.authenticate('jwt', session: false );
              done();
              );
              after(function (done)
              console.log('after hook');
              passport.authenticate.restore();
              done();
              );
              describe('POST /route', function ()
              it('should post', function (done)
              console.log('starting test');
              const server = require('../../app'); // <= require it AFTER creating the stub
              chai.request(server)
              .post('/route')
              .end(function (err, res)
              expect(res).to.have.status(200);
              done();
              );
              );
              );
              );





              share|improve this answer

























                0












                0








                0









                Your code calls passport.authenticate as soon as it runs, and it runs as soon as it is required.



                Because you are requiring the code at the beginning of the test before the stub has been created your code ends up calling the real passport.authenticate.



                In order for code like this to call the stub you must set up your stub before you require your code:



                const chai = require('chai');
                const chaiHttp = require('chai-http');
                const sinon = require('sinon');
                const passport = require('passport');
                // const server = require('../../app'); <= don't require your code here...
                const expect = chai.expect;

                chai.use(chaiHttp);
                describe('route', function ()
                before(function (done)
                sinon.stub(passport, 'authenticate').callsFake(function (test, args)
                console.log('Auth stub');
                );
                console.log('stub registered');
                passport.authenticate('jwt', session: false );
                done();
                );
                after(function (done)
                console.log('after hook');
                passport.authenticate.restore();
                done();
                );
                describe('POST /route', function ()
                it('should post', function (done)
                console.log('starting test');
                const server = require('../../app'); // <= require it AFTER creating the stub
                chai.request(server)
                .post('/route')
                .end(function (err, res)
                expect(res).to.have.status(200);
                done();
                );
                );
                );
                );





                share|improve this answer















                Your code calls passport.authenticate as soon as it runs, and it runs as soon as it is required.



                Because you are requiring the code at the beginning of the test before the stub has been created your code ends up calling the real passport.authenticate.



                In order for code like this to call the stub you must set up your stub before you require your code:



                const chai = require('chai');
                const chaiHttp = require('chai-http');
                const sinon = require('sinon');
                const passport = require('passport');
                // const server = require('../../app'); <= don't require your code here...
                const expect = chai.expect;

                chai.use(chaiHttp);
                describe('route', function ()
                before(function (done)
                sinon.stub(passport, 'authenticate').callsFake(function (test, args)
                console.log('Auth stub');
                );
                console.log('stub registered');
                passport.authenticate('jwt', session: false );
                done();
                );
                after(function (done)
                console.log('after hook');
                passport.authenticate.restore();
                done();
                );
                describe('POST /route', function ()
                it('should post', function (done)
                console.log('starting test');
                const server = require('../../app'); // <= require it AFTER creating the stub
                chai.request(server)
                .post('/route')
                .end(function (err, res)
                expect(res).to.have.status(200);
                done();
                );
                );
                );
                );






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 8 at 7:43









                brian-lives-outdoorsbrian-lives-outdoors

                11k1930




                11k1930





























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55056593%2fsinon-stub-is-being-ignored-outside-of-the-test-file%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

                    Алба-Юлія

                    Захаров Федір Захарович