在回调中执行测试

时间:2015-08-20 14:11:07

标签: javascript jasmine karma-runner systemjs

是否可以执行回调中的测试?例如,我有

System.import("mymodule").then(function(Mymodule) {
  describe("Mymodule", function() {
    it("does something", function() {
      expect(Mymodule.dosomething()).toBeTruthy();
    });
  });
});

此测试从未运行过。简单的setTimeout

也是如此
var Mymodule = { dosomething: function(){ return true; } };

setTimeout(function() {
  describe("Mymodule", function() {
    it("does something", function() {
      expect(Mymodule.dosomething()).toBeTruthy();
    });
  });
});

有没有办法做到这一点?否则我有很多问题,包括异步时尚的模块

2 个答案:

答案 0 :(得分:0)

来自:http://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support

您应该以同步方式描述测试,接受done函数中的it回调,执行一些异步操作并在完成后调用回调。

来自茉莉花网站的示例

  describe("long asynchronous specs", function() {
    var originalTimeout;
    beforeEach(function() {
      originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
      jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
    });

    it("takes a long time", function(done) {
      setTimeout(function() {
        done();
      }, 9000);
    });

    afterEach(function() {
      jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
    });
  });
});

答案 1 :(得分:0)

我终于解决了这个问题。我将此文件列为最后一个

basePath = "/base/spec/"

modules = []

for own fileName, fileHash of window.__karma__.files
  if fileName.indexOf(basePath) is 0
    isRunner   = fileName.indexOf("spec_runner") >= 0
    isRunner ||= fileName.indexOf("spec_helper") >= 0
    unless isRunner
      moduleName = fileName.replace(basePath, "")
      moduleName = moduleName.replace(".js", "")
      modules.push(path: fileName, name: moduleName)

mappedModules = {}
baseSpecsPath = "http://localhost:9876"
specModules   = []

for module in modules
  mappedModules[module.name] = baseSpecsPath + module.path
  specModules.push(module.name)

System.config
  baseURL: "http://localhost:4567/javascripts/"
  map:     mappedModules

moduleImports = specModules.map (moduleName) ->
  System.import(moduleName)

Promise.all(moduleImports).then ->
  window.__karma__.start     = window.__lastKarmaStart__
  window.__lastKarmaStart__  = null
  delete window.__lastKarmaStart__
  window.__karma__.start()

它做了以下事情:

  • 暂时禁用业力启动功能,将其替换为空值
  • 获取存储在System.register中的每项测试,针对所有测试运行System.import
  • 完成所有导入后,它会附加__karma__start并执行它,运行Jasmine