简体   繁体   English

您如何断言Ember.js中使用了运行循环?

[英]How do you assert a run loop was used in Ember.js?

I have this code inside an Ember service: 我在Ember服务中有以下代码:

return new Promise((resolve, reject) => {
  semaphore.take(() => {
    this.get('limiter').removeTokens(1, () => {
      semaphore.leave();

      this.get('requestSender').sendRequest(url).then(data => {
        run(null, resolve, cache.put(url, data, cacheTime));
      }).catch(function() {
        run(null, reject, arguments);
      });
    });
  });
});

I'm going through the limiter callback, so I need a run loop (to my understanding). 我正在经历限制器回调,所以我需要一个运行循环(据我所知)。 I would like to assert in a unit test that a run loop was used. 我想在单元测试中断言使用了运行循环。 I can assert the promise resolves the correct value from the cache, but I don't know how to verify a run loop was used. 我可以断言promise会从缓存中解析出正确的值,但是我不知道如何验证是否使用了运行循环。 In other words, I could remove the run call and all my tests would still pass, which is not desirable. 换句话说,我可以删除run调用,并且我的所有测试仍将通过,这是不希望的。

Things I've thought of that I don't want to resort to: 我想到的我不想诉诸的事情:

  • I could use Ember.run instead of run and use stubbing and restoring, but I like to deconstruct globals at the top of the file ( const { run } = Ember; ), so I would not like to sacrifice that just for a test. 我可以使用Ember.run代替run并使用存根和还原,但是我想在文件顶部解构全局变量( const { run } = Ember; ),所以我不想为了测试而牺牲它。
  • I could wrap the run loop call in another Ember service so I can stub it, but that seems like overkill. 我可以将run loop调用包装在另一个Ember服务中,以便对它进行存根处理,但这似乎有点过头了。

Basically I'm wondering if there are any events that fire when a run loop is entered that I can listen to in a test. 基本上,我想知道在进入运行循环时是否有任何事件可以触发我可以在测试中收听的事件。 It's OK if involves Ember privates. 如果涉及到Ember私人,那就可以了。

You could add argument to your method which would make your method of service more "testable". 您可以在方法中添加参数,这将使您的服务方法更“可测试”。 Analyse this fragment of code: 分析这段代码:

const Ember = {
  run() {
    console.log('ORIGINAL METHOD');
  }
};
const { run } = Ember;

const service = {
  method(runMethod) {
    let runToCall = runMethod ? runMethod : run;
    runToCall();
  }
};

// in application
service.method();

// in tests
function mockedRun() {
  console.log('REPLACED METHOD');  
};

service.method(mockedRun);

Which outputs: 哪个输出:

ORIGINAL METHOD 原始方法

REPLACED METHOD 替代方法

Here's demo . 这是演示

Eventually you could use: 最终,您可以使用:

I could wrap the run loop call in another Ember service so I can stub it, but that seems like overkill. 我可以将run loop调用包装在另一个Ember服务中,以便对它进行存根处理,但这似乎有点过头了。

But seems like passing function as argument is simpler. 但是似乎将函数作为参数传递更为简单。

Test will fail if run loop is not started because you'll get an assertion. 如果未启动运行循环,则测试将失败,因为您将获得一个断言。 Is this not enough? 这还不够吗?

Why do you need to assert that run loop was used? 为什么需要断言使用了运行循环?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM