我在这里遇到了一些奇怪的行为,想知道是否有人知道它为什么会发生。我写了一个简单的Ember QUnit测试,想在每次测试之间共享一些数据,只是为了减少混乱。
import Ember from 'ember'
import { moduleFor, test } from 'ember-qunit';
let create = Ember.Object.create;
let shared = create({});
shared.stardardData1 = create({ id: 1 });
shared.stardardData2 = create({ id: 2 });
moduleFor('controller:foo', 'description', {
beforeEach() { ... }
afterEach() { ... }
}
test('should do things', function () {
let myGroup = [shared.standardData1, shared.standardData2];
}
这里有几件事:
this._initProperties is not a function
moduleFor
和test
let a = 1
中执行类似beforeEach
的操作,但似乎无法在测试中引用它们我注意到QUnit文档说它们已经消除了全局变量。这可能会在这方面发挥作用吗? https://qunitjs.com/upgrade-guide-2.x/
PS:拥有一次只设置模块而不是每次都
的东西会很不错这是堆栈跟踪:
Promise rejected before should do things: this._initProperties is not a function Source: TypeError: this._initProperties is not a function at create (http://localhost:7357/assets/vendor.js:46461:14) at Object.beforeEach (http://localhost:7357/assets/tests.js:185:20) at http://localhost:7357/assets/test-support.js:6586:31 at tryCatch (http://localhost:7357/assets/vendor.js:61631:14) at invokeCallback (http://localhost:7357/assets/vendor.js:61646:15) at publish (http://localhost:7357/assets/vendor.js:61614:9) at http://localhost:7357/assets/vendor.js:41408:7 at invoke (http://localhost:7357/assets/vendor.js:11120:16) at Object.flush (http://localhost:7357/assets/vendor.js:11184:11) at Object.flush (http://localhost:7357/assets/vendor.js:10992:17)
实际上我认为这可能与全局变量没有关系。我还添加了(之前没有包含)let create = Ember.Object.create
只是为了保存一些打字(并用调用create(object)
包裹上面的对象。摆脱它并使用长形式似乎摆脱了这个错误虽然......
答案 0 :(得分:2)
问题的最后一部分是实际问题。
当你这样做时
let create = Ember.Object.create
您从create
中提取函数Ember.Object
并创建一个新的引用,作为普通函数。
根据JS绑定规则,当您将函数作为普通函数调用时,其中的this
将绑定到全局对象(或严格模式下的undefined
)。另一方面,当您将函数作为对象上的方法调用(即直接在Ember.Object
上调用它)时,会将this
绑定到该对象。
这就是为什么this
在create
内未定义,因此this._initProperties
不是函数。
以下是正在发生的事情的演示:
// an object with a method
var obj = {
getThis: function() {
return this;
}
};
// an extracted reference to the method
var extractedGetThis = obj.getThis;
// this binds to the object
console.log(
obj.getThis() === obj // true
);
// this binds globally
console.log(
extractedGetThis() === window // true
);