如何调用$(document).ready(function(){…});从另一个文件JS

时间:2018-08-21 11:10:57

标签: javascript sinon teaspoon

我想知道如何在不从另一个js文件重构的情况下调用以下函数。

$(document).ready(function() {

  check();

  function check () {
    setTimeout(function(){
      location.reload(true);
    }, 10000);
  }

});

我看到这个问题存在很久了,但是我不明白如何将答案用于我的函数。 StackOverflow answer from another question

我想从链接中看到有关我的函数和建议的解决方案的示例。

我的示例无法正常运行:

//= require rspec_helper
//= require background_index
//= require sinon



describe("Background Index, timeout after 10s", function() {
  // Tweak for testing
  var doc_ready = $.readyList[0]();

  it ("Reload the location", function(){
    clock = sinon.useFakeTimers();

    var check = doc_ready.check();
    var set_timeout = doc_ready.setTimeout();
    /*var stub_check = sinon.stub(check, "check");
    var stub_timeout = sinon.stub(timeout, "setTimeout");*/


    timedOut = false;



    setTimeout(function () {
      timedOut = true;
    }, 1000);


    timedOut.should.be.false;
    clock.tick(10010);
    timedOut.should.be.true;

    clock.restore();
  });

});

1 个答案:

答案 0 :(得分:0)

这是根据您粘贴的答案重写的。

$(document).ready(check);

  function check () {
    setTimeout(function(){
      location.reload(true);
    }, 10000);
  }   

// In the test file
TestFile.prototype.testDocumentReadyContents = function () {
  check();
}

一种更好的方法是使用<script src="./path-to-file">将HTML中的所有JS文件包括在内,然后按照希望它们被调用的顺序调用这些函数。

相关问题