来自 controllers / cart.js 的代码:
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/resources/dojo.css">
<link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dijit/themes/tundra/tundra.css">
<div id="navtool" >
<div data-dojo-type="dijit/form/Button" id="zoomin" >Zoom In</div>
<div data-dojo-type="dijit/form/Button" id="zoomout" >Zoom Out</div>
<div data-dojo-type="dijit/form/Button" id="zoomfullext" >Full Extent</div>
<div data-dojo-type="dijit/form/Button" id="zoomprev" >Prev Extent</div>
<div data-dojo-type="dijit/form/Button" id="zoomnext" >Next Extent</div>
<div data-dojo-type="dijit/form/Button" id="pan" >Pan</div>
<div data-dojo-type="dijit/form/Button" id="deactivate" >Deactivate</div>
</div>
<button onclick="showDialog2();">show without underlay</button>
此计算属性循环遍历模型中的所有元素,添加export default Ember.Controller.extend({
cartTotal: Ember.computed('model.@each.subTotal', function() {
return this.model.reduce(function(subTotal, product) {
var total = subTotal + product.get('subTotal');
return total;
}, 0);
})
)};
属性的所有值,返回subTotal
。
推车test.js
cart total
测试因import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';
moduleFor('controller:cart', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
});
test('it exists', function(assert) {
var controller = this.subject();
assert.ok(controller);
});
test('cartTotal function exists', function(assert) {
var controller = this.subject();
assert.equal(controller.get('cartTotal'), 30, 'The cart total function exists');
});
而失败,因为它显然没有模型可以循环。
如何模拟TypeError: Cannot read property 'reduce' of null
计算属性的依赖关系以使测试通过?
谢谢!
答案 0 :(得分:6)
沿着这些方向可能有什么?
import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';
var products = [
Ember.Object.create({ name: 'shoe', subTotal: 10 }),
Ember.Object.create({ name: 'shirt', subTotal: 20 })];
var model = Ember.ArrayProxy.create({
content: Ember.A(products)
});
moduleFor('controller:cart', {
beforeEach() {
this.controller = this.subject();
}
});
test('cartTotal', function(assert) {
this.controller.set('model', model);
assert.equal(this.controller.get('cartTotal'), 30, 'The cart total function exists');
});
答案 1 :(得分:2)
解决这个问题的一种方法是在beforeEach
钩子中存根模型:
var sampleModel = [ // sample data that follows your actual model structure ]
moduleFor('controller:cart', {
beforeEach() {
this.controller = this.subject(); // allows you to access it in the tests without having to redefine it each time
this.controller.set('model', sampleModel);
}
});