gpt4 book ai didi

unit-testing - Ember Controller 上的单元测试计算属性

转载 作者:行者123 更新时间:2023-12-04 04:48:42 24 4
gpt4 key购买 nike

来 self 的 controllers/cart.js 的代码:

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 属性的所有值,返回 cart total

cart-test.js

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 因为它显然没有要循环的模型。

如何模拟 cartTotal 计算属性的依赖关系以使测试通过?

谢谢!

最佳答案

也许是这样的?

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');
});

关于unit-testing - Ember Controller 上的单元测试计算属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31294392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com