Mirage 在验收测试中响应 404

Mirage responds 404 on acceptances tests

这几天一直在和海市蜃楼纠缠,一直没有想出解决办法。

即使使用非常简化的配置(见下文),每当在 验收测试 中调用 Mirage 时,它​​都会以 404 错误代码响应。 当我为我的应用程序提供服务并查看浏览器控制台时,这些调用确实有效 (Mirage 以 200 状态响应,这里的数据是我在下面设置的 hello@world.com)。

这是我的 mirage/config.js 文件

// mirage/config.js

export default function() {
  this.get('/users', function() {
    return {
      data: [{
        type: 'user',
        id: 'first',
        attributes: {
          email: 'hello@world.com'
        }
      }]
    };
  });
}

这是我的 app/routes/home.js

// app/routes/home.js
import Route from '@ember/routing/route';

export default Route.extend({
  model() { return this.store.findAll('user'); }
});

这是失败的测试

import { module, test } from 'qunit';
import { visit, currentURL } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';

module('Acceptance | home', function(hooks) {
  setupApplicationTest(hooks);

  test('visiting /home', async function(assert) {
    await visit('/home');

    assert.equal(currentURL(), '/home');
  });
});

带有此消息:

Promise rejected during "visiting /home": Ember Data Request GET /users 
returned a 404
Payload (Empty Content-Type)
Not found: /users@ 152 ms
Source:     
Error: Ember Data Request GET /users returned a 404
Payload (Empty Content-Type)
Not found: /users
    at ErrorClass.EmberError 
(http://localhost:7357/assets/vendor.js:24125:25)
    at ErrorClass.AdapterError 
(http://localhost:7357/assets/vendor.js:157167:15)
    at new ErrorClass (http://localhost:7357/assets/vendor.js:157185:22)
    at Class.handleResponse 
(http://localhost:7357/assets/vendor.js:169227:18)
    at ajaxError (http://localhost:7357/assets/vendor.js:169720:25)
    at Class.hash.error 
(http://localhost:7357/assets/vendor.js:169308:23)
    at fire (http://localhost:7357/assets/vendor.js:3607:31)
    at Object.fireWith [as rejectWith] 
(http://localhost:7357/assets/vendor.js:3737:7)
    at done (http://localhost:7357/assets/vendor.js:9646:14)
    at XMLHttpRequest.<anonymous> 
(http://localhost:7357/assets/vendor.js:9887:9)

谢谢

您确定 Mirage 在您的测试中甚至 运行 吗?

如果您使用的是 Ember 的最新版本,Mirage 的默认初始化程序可能不是 运行。 (这需要修复。)

您可能想要 the latest release notes 阅读,并确保您使用的是 0.4.2+ 版本。

在新的测试方式中,您需要做类似

的事情
  import { module, test } from 'qunit';
  import { visit, currentURL } from '@ember/test-helpers';
  import { setupApplicationTest } from 'ember-qunit';
+ import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';

  module('Acceptance | login', function(hooks) {
    setupApplicationTest(hooks);
+   setupMirage(hooks);

    test('visiting /login', async function(assert) {
      await visit('/login');
      assert.equal(currentURL(), '/login');
    });
  });