How to test a method with timeout after calling another method in sinon The Next CEO of Stack OverflowHow do I test a private function or a class that has private methods, fields or inner classes?How to manage a redirect request after a jQuery Ajax callHow do I redirect to another webpage?How to check if a string “StartsWith” another string?How do I test for an empty JavaScript object?How do I include a JavaScript file in another JavaScript file?How to move an element into another element?How do I return the response from an asynchronous call?How to increase timeout for a single test case in mochaHow to dispatch a Redux action with a timeout?

Anatomically Correct Mesopelagic Aves

What can we do to stop prior company from asking us questions?

Bulk API v2 Get Job Status Failing - InvalidBatch : Field name not found

When did Lisp start using symbols for arithmetic?

What does "Its cash flow is deeply negative" mean?

How easy is it to start Magic from scratch?

Does the Brexit deal have to be agreed by both Houses?

Why doesn't a table tennis ball float on the surface? How do we calculate buoyancy here?

How to safely derail a train during transit?

What is the difference between "behavior" and "behaviour"?

Unreliable Magic - Is it worth it?

ls Ordering[Ordering[list]] optimal?

How would telepathy be more difficult than verbal communication?

Is HostGator storing my password in plaintext?

Return of the Riley Riddles in Reverse

Can the Reverse Gravity spell affect the Meteor Swarm spell?

What's the point of interval inversion?

Why is Miller's case titled R (Miller)?

Can a caster that cast Polymorph on themselves stop concentrating at any point even if their Int is low?

How to write papers efficiently when English isn't my first language?

How to Reset Passwords on Multiple Websites Easily?

How do spells that require an ability check vs. the caster's spell save DC work?

India just shot down a satellite from the ground. At what altitude range is the resulting debris field?

I believe this to be a fraud



How to test a method with timeout after calling another method in sinon



The Next CEO of Stack OverflowHow do I test a private function or a class that has private methods, fields or inner classes?How to manage a redirect request after a jQuery Ajax callHow do I redirect to another webpage?How to check if a string “StartsWith” another string?How do I test for an empty JavaScript object?How do I include a JavaScript file in another JavaScript file?How to move an element into another element?How do I return the response from an asynchronous call?How to increase timeout for a single test case in mochaHow to dispatch a Redux action with a timeout?










1















How can I test a property inside a timeout from another called method?



I want to test a property if it's changed inside the setTimeout but using sinons useFakeTimer doesn't seems to work. Or am I missing something?



To illustrate here's my code



const fs = require('fs');

function Afunc (context)
this.test = context;


module.exports = Afunc;

Afunc.prototype.start = function ()
const self = this;

this.readFile(function (error, content)
setTimeout(function ()
self.test = 'changed';
self.start();
, 1000);
);


Afunc.prototype.readFile = function (callback)
fs.readFile('./file', function (error, content)
if (error)
return callback(error);


callback(null, content);
)



And here's what I have so far.



describe('Afunc', function () 
let sandbox, clock, afunc;

before(function ()
sandbox = sinon.createSandbox();
);

beforeEach(function ()
clock = sinon.useFakeTimers();

afunc = new Afunc('test');

sandbox.stub(afunc, 'readFile').yieldsAsync(null);
);

afterEach(function ()
clock.restore();
sandbox.restore();
);

it('should change test to `changed`', function ()
afunc.start();

clock.tick(1000);

afunc.test.should.be.equal('changed');

);
);


after the clock.tick check the property test is not changed.



Any help is deeply appreciated! Thanks in advance.










share|improve this question




























    1















    How can I test a property inside a timeout from another called method?



    I want to test a property if it's changed inside the setTimeout but using sinons useFakeTimer doesn't seems to work. Or am I missing something?



    To illustrate here's my code



    const fs = require('fs');

    function Afunc (context)
    this.test = context;


    module.exports = Afunc;

    Afunc.prototype.start = function ()
    const self = this;

    this.readFile(function (error, content)
    setTimeout(function ()
    self.test = 'changed';
    self.start();
    , 1000);
    );


    Afunc.prototype.readFile = function (callback)
    fs.readFile('./file', function (error, content)
    if (error)
    return callback(error);


    callback(null, content);
    )



    And here's what I have so far.



    describe('Afunc', function () 
    let sandbox, clock, afunc;

    before(function ()
    sandbox = sinon.createSandbox();
    );

    beforeEach(function ()
    clock = sinon.useFakeTimers();

    afunc = new Afunc('test');

    sandbox.stub(afunc, 'readFile').yieldsAsync(null);
    );

    afterEach(function ()
    clock.restore();
    sandbox.restore();
    );

    it('should change test to `changed`', function ()
    afunc.start();

    clock.tick(1000);

    afunc.test.should.be.equal('changed');

    );
    );


    after the clock.tick check the property test is not changed.



    Any help is deeply appreciated! Thanks in advance.










    share|improve this question


























      1












      1








      1








      How can I test a property inside a timeout from another called method?



      I want to test a property if it's changed inside the setTimeout but using sinons useFakeTimer doesn't seems to work. Or am I missing something?



      To illustrate here's my code



      const fs = require('fs');

      function Afunc (context)
      this.test = context;


      module.exports = Afunc;

      Afunc.prototype.start = function ()
      const self = this;

      this.readFile(function (error, content)
      setTimeout(function ()
      self.test = 'changed';
      self.start();
      , 1000);
      );


      Afunc.prototype.readFile = function (callback)
      fs.readFile('./file', function (error, content)
      if (error)
      return callback(error);


      callback(null, content);
      )



      And here's what I have so far.



      describe('Afunc', function () 
      let sandbox, clock, afunc;

      before(function ()
      sandbox = sinon.createSandbox();
      );

      beforeEach(function ()
      clock = sinon.useFakeTimers();

      afunc = new Afunc('test');

      sandbox.stub(afunc, 'readFile').yieldsAsync(null);
      );

      afterEach(function ()
      clock.restore();
      sandbox.restore();
      );

      it('should change test to `changed`', function ()
      afunc.start();

      clock.tick(1000);

      afunc.test.should.be.equal('changed');

      );
      );


      after the clock.tick check the property test is not changed.



      Any help is deeply appreciated! Thanks in advance.










      share|improve this question
















      How can I test a property inside a timeout from another called method?



      I want to test a property if it's changed inside the setTimeout but using sinons useFakeTimer doesn't seems to work. Or am I missing something?



      To illustrate here's my code



      const fs = require('fs');

      function Afunc (context)
      this.test = context;


      module.exports = Afunc;

      Afunc.prototype.start = function ()
      const self = this;

      this.readFile(function (error, content)
      setTimeout(function ()
      self.test = 'changed';
      self.start();
      , 1000);
      );


      Afunc.prototype.readFile = function (callback)
      fs.readFile('./file', function (error, content)
      if (error)
      return callback(error);


      callback(null, content);
      )



      And here's what I have so far.



      describe('Afunc', function () 
      let sandbox, clock, afunc;

      before(function ()
      sandbox = sinon.createSandbox();
      );

      beforeEach(function ()
      clock = sinon.useFakeTimers();

      afunc = new Afunc('test');

      sandbox.stub(afunc, 'readFile').yieldsAsync(null);
      );

      afterEach(function ()
      clock.restore();
      sandbox.restore();
      );

      it('should change test to `changed`', function ()
      afunc.start();

      clock.tick(1000);

      afunc.test.should.be.equal('changed');

      );
      );


      after the clock.tick check the property test is not changed.



      Any help is deeply appreciated! Thanks in advance.







      javascript unit-testing mocha settimeout sinon






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 21 at 16:32







      per.eight

















      asked Mar 21 at 16:07









      per.eightper.eight

      176315




      176315






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Just change this:



          sandbox.stub(afunc, 'readFile').yieldsAsync(null);


          ...to this:



          sandbox.stub(afunc, 'readFile').yields();


          ...and it should work.




          Details



          yieldsAsync defers using process.nextTick so the callback passed to readFile wasn't getting called until "all instructions in the current call stack are processed"...which in this case was your test function.



          So the callback that changed afunc.test to 'changed' was getting called...but not until after your test completed.






          share|improve this answer























          • You're a life saver man! you deserve a fresh cold beer! Big thanks!

            – per.eight
            Mar 21 at 16:55











          • @per.eight glad I could help :)

            – brian-lives-outdoors
            Mar 21 at 16:57











          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%2f55284707%2fhow-to-test-a-method-with-timeout-after-calling-another-method-in-sinon%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









          1














          Just change this:



          sandbox.stub(afunc, 'readFile').yieldsAsync(null);


          ...to this:



          sandbox.stub(afunc, 'readFile').yields();


          ...and it should work.




          Details



          yieldsAsync defers using process.nextTick so the callback passed to readFile wasn't getting called until "all instructions in the current call stack are processed"...which in this case was your test function.



          So the callback that changed afunc.test to 'changed' was getting called...but not until after your test completed.






          share|improve this answer























          • You're a life saver man! you deserve a fresh cold beer! Big thanks!

            – per.eight
            Mar 21 at 16:55











          • @per.eight glad I could help :)

            – brian-lives-outdoors
            Mar 21 at 16:57















          1














          Just change this:



          sandbox.stub(afunc, 'readFile').yieldsAsync(null);


          ...to this:



          sandbox.stub(afunc, 'readFile').yields();


          ...and it should work.




          Details



          yieldsAsync defers using process.nextTick so the callback passed to readFile wasn't getting called until "all instructions in the current call stack are processed"...which in this case was your test function.



          So the callback that changed afunc.test to 'changed' was getting called...but not until after your test completed.






          share|improve this answer























          • You're a life saver man! you deserve a fresh cold beer! Big thanks!

            – per.eight
            Mar 21 at 16:55











          • @per.eight glad I could help :)

            – brian-lives-outdoors
            Mar 21 at 16:57













          1












          1








          1







          Just change this:



          sandbox.stub(afunc, 'readFile').yieldsAsync(null);


          ...to this:



          sandbox.stub(afunc, 'readFile').yields();


          ...and it should work.




          Details



          yieldsAsync defers using process.nextTick so the callback passed to readFile wasn't getting called until "all instructions in the current call stack are processed"...which in this case was your test function.



          So the callback that changed afunc.test to 'changed' was getting called...but not until after your test completed.






          share|improve this answer













          Just change this:



          sandbox.stub(afunc, 'readFile').yieldsAsync(null);


          ...to this:



          sandbox.stub(afunc, 'readFile').yields();


          ...and it should work.




          Details



          yieldsAsync defers using process.nextTick so the callback passed to readFile wasn't getting called until "all instructions in the current call stack are processed"...which in this case was your test function.



          So the callback that changed afunc.test to 'changed' was getting called...but not until after your test completed.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 21 at 16:53









          brian-lives-outdoorsbrian-lives-outdoors

          10.4k1928




          10.4k1928












          • You're a life saver man! you deserve a fresh cold beer! Big thanks!

            – per.eight
            Mar 21 at 16:55











          • @per.eight glad I could help :)

            – brian-lives-outdoors
            Mar 21 at 16:57

















          • You're a life saver man! you deserve a fresh cold beer! Big thanks!

            – per.eight
            Mar 21 at 16:55











          • @per.eight glad I could help :)

            – brian-lives-outdoors
            Mar 21 at 16:57
















          You're a life saver man! you deserve a fresh cold beer! Big thanks!

          – per.eight
          Mar 21 at 16:55





          You're a life saver man! you deserve a fresh cold beer! Big thanks!

          – per.eight
          Mar 21 at 16:55













          @per.eight glad I could help :)

          – brian-lives-outdoors
          Mar 21 at 16:57





          @per.eight glad I could help :)

          – brian-lives-outdoors
          Mar 21 at 16:57



















          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%2f55284707%2fhow-to-test-a-method-with-timeout-after-calling-another-method-in-sinon%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

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해