简体   繁体   中英

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

I have this code inside an Ember service:

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. In other words, I could remove the run call and all my tests would still pass, which is not desirable.

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.
  • I could wrap the run loop call in another Ember service so I can stub it, but that seems like overkill.

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.

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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