简体   繁体   English

Ember Octane:对控制器进行单元测试异步操作

[英]Ember Octane: Unit testing async action on controller

Having the following controller and tests:具有以下控制器和测试:

app/controllers/application.js应用程序/控制器/application.js

import Controller from '@ember/controller';
import { action } from '@ember/object';

export default class ApplicationController extends Controller {
  flag = false;

  @action
  raiseFlag() {
    this.flag = true;
  }

  @action
  async raiseFlagAsync() {
    await new Promise(resolve => setTimeout(resolve, 1000));
    this.flag = true;
  }
}

tests/unit/controllers/application-test.js测试/单元/控制器/application-test.js

import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';

module('Unit | Controller | application', function(hooks) {
  setupTest(hooks);

  test('it raises flag', function(assert) {
    let controller = this.owner.lookup('controller:application');
    assert.equal(controller.flag, false);
    controller.send('raiseFlag');
    assert.equal(controller.flag, true);
  });

  test('it raises flag asyncronously', async function(assert) {
    let controller = this.owner.lookup('controller:application');
    assert.equal(controller.flag, false);
    await controller.send('raiseFlagAsync');
    assert.equal(controller.flag, true);
  });
});

The first test case passes.第一个测试用例通过。 The second test case fails (the async one)第二个测试用例失败(异步的)

What is the ember-octane way of waiting for the async action?等待异步操作的 ember-octane 方式是什么?

The trick here is to not use send !这里的诀窍是不要使用send Generally I would use send only if you need to bubble actions in the route chain.通常,当您需要在路由链中冒泡操作时,我才会使用send Its a bit a old concept and it has no return value .它有点旧概念,它没有返回值 So await controller.send will not work.所以await controller.send无法正常工作。

You should just invoke the action directly:您应该直接调用该操作:

test('it raises flag asyncronously', async function(assert) {
  let controller = this.owner.lookup('controller:application');
  assert.equal(controller.flag, false);
  await controller.raiseFlagAsync();
  assert.equal(controller.flag, true);
});

Not sure why it was so hard to find this information, maybe bad SEO.不知道为什么很难找到这些信息,也许是糟糕的 SEO。

import { waitUntil } from '@ember/test-helpers';

test('it raises flag asyncronously', async function(assert) {
  let controller = this.owner.lookup('controller:application');
  assert.equal(controller.flag, false);
  controller.send('raiseFlagAsync');

  await waitUntil(() => controller.flag === true);
});

If anyone comes up with a more ember-ish answer I'll accept that once instead如果有人想出一个更灰烬的答案,我会接受一次

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

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