[英]Strange behavior in javascript argument inside a global Object
在Global Javascript對象中的參數中有一個奇怪的行為:我需要用jasmine.js測試我的代碼,但是我不能將期望的值傳遞給參數,總是在jasmine測試中返回undefined。
//My model
myGlobalObject = function(){
_myCart = function(){
return {
total : 0,
products : []
}
}
return {
init: function(strangeArgument){
console.log(strangeArgument) //this return undefined in jasmine test
},
myCart : _myCart,
addProduct : function(Products){
return _myCart()
},
.....
}
}
考試:
const c{
empty : {
total: {
beforeVAT: 0,
afterVAT: 0,
VAT: 0
},
products: []
}
}
beforeEach(() => {
this.instance = myGlobalObject();
this.instance.init();
this.productWithoutQuantity = Object.assign({}, _.productA);
delete this.productWithoutQuantity.quantity;
this.productWithQuantity = Object.assign({}, _.productB);
});
test(`the cart should be empty`, () => {
expect(this.instance.getCart()).toEqual(c.empty);
});
.... more tests
而我的主要js:
var e = myGlobalObject();
var initialState = function (){
return {
total: {
beforeVAT: 0,
afterVAT: 0,
VAT: 0
},
products: []
}
}
e.init(initialState);
怎么了?
雖然我在這里未能完全理解OP的意圖,但以下是我對這個問題的看法
_myCart
可以是局部變量,因為它似乎沒有任何更大的目的,至少從OP提供的代碼
對instance.init
的調用可以是空括號或合法變量 - 取決於OP在這里嘗試實現的內容。
我已經包含了main.js代碼片段以及testVariable.instance.init();
(簡單來說,如果@Bergi評論它是未定義的,那么它是未定義的)
在這里看到它
myGlobalObject = function() { this._myCart = function() { return { total: 0, products: [] } } return { init: function(strangeArgument) { console.log(strangeArgument) }, myCart: this._myCart, addProduct: function(Products) { return this._myCart() } } } var e = myGlobalObject(); var initialState = function() { return { total: { beforeVAT: 0, afterVAT: 0, VAT: 0 }, products: [] } } e.init(initialState); describe('ajax test suite', function() { var testVariable = {} var c = { empty: { total: 0, products: [] } } beforeEach(function() { testVariable.instance = myGlobalObject(); testVariable.instance.init("hello"); testVariable.instance.init(); }); it('the cart should be empty', function() { expect(testVariable.instance.myCart()).toEqual(c.empty); }); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.