Ember JS教程:TypeError:无法读取属性' maps'未定义的

时间:2017-05-09 00:41:58

标签: javascript ember.js ember-testing

我目前正在他们的网站上浏览官方的EmberJS教程,我在this part。当我运行ember serve时,一切都在应用程序中完美运行,但问题是当我为新服务运行单元测试时。我正在运行ember test --server,我收到一个错误,我在下面截取了屏幕截图:

enter image description here

单元测试代码:

import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';

const DUMMY_ELEMENT = {};

let MapUtilStub = Ember.Object.extend({
  createMap(element, location) {
    this.assert.ok(element, 'createMap called with element');
    this.assert.ok(location, 'createMap called with location');
    return DUMMY_ELEMENT;
  }
});

moduleFor('service:maps', 'Unit | Service | maps', {
  needs: ['util:google-maps']
});

test('should create a new map if one isnt cached for location', function (assert) {
  assert.expect(4);
  let stubMapUtil = MapUtilStub.create({ assert });
  let mapService = this.subject({ mapUtil: stubMapUtil });
  let element = mapService.getMapElement('San Francisco');
  assert.ok(element, 'element exists');
  assert.equal(element.className, 'map', 'element has class name of map');
});

test('should use existing map if one is cached for location', function (assert) {
  assert.expect(1);
  let stubCachedMaps = Ember.Object.create({
    sanFrancisco: DUMMY_ELEMENT
  });
  let mapService = this.subject({ cachedMaps: stubCachedMaps });
  let element = mapService.getMapElement('San Francisco');
  assert.equal(element, DUMMY_ELEMENT, 'element fetched from cache');
});

从本教程中,我的理解是this.subject({ cachedMaps: stubCachedMaps })将为我设置所有maps,但似乎服务本身可能未定义,导致没有属性maps。这是正确的吗?可能导致这种情况的原因是什么?

运行ember --version的系统规格:

  • ember-cli:2.13.0
  • node:6.8.1
  • os:darwin x64

3 个答案:

答案 0 :(得分:3)

所以碰到了同样的事情。看起来在每个测试之间,先前的存根被擦除。所以我在第二次测试中再次添加它并且效果很好:

test('should use existing map if one is cached for location', 
  function(assert) {
    assert.expect(1);
    let stubCachedMaps = Ember.Object.create({
      sanFrancisco: DUMMY_ELEMENT
    });
    let stubMapUtil = MapUtilStub.create({ assert });
    let mapService = this.subject({ mapUtil: stubMapUtil, cachedMaps: stubCachedMaps });
    let element = mapService.getMapElement('San Francisco');
    assert.equal(element, DUMMY_ELEMENT, 'element fetched from cache');
});

答案 1 :(得分:1)

您发布的测试代码应该有效,因此问题必须在其他地方。

您可以将其余代码与教程应用的完整版本进行比较吗?您可以克隆回购@ https://github.com/ember-learn/super-rentals

所有测试都运行良好,包括地图服务。

答案 2 :(得分:1)

我也在同样的事情上奔跑。 @cythrawll的解决方案有效,但它不是TypeError: Cannot read property 'maps' of undefined错误的根本原因。

在教程中,他们忘了添加

<script src="https://maps.googleapis.com/maps/api/js?v=3.22"></script>
test/index.html文件中

。已经报告了Issue