[英]Strange behavior in javascript argument inside a global Object
there is a strange behavior in an argument inside a Global Javascript object: I need to test my code with jasmine.js, but I can´t pass the expected value to the argument always return undefined in jasmine test. 在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()
},
.....
}
}
The test: 考试:
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
And my main js: 而我的主要js:
var e = myGlobalObject();
var initialState = function (){
return {
total: {
beforeVAT: 0,
afterVAT: 0,
VAT: 0
},
products: []
}
}
e.init(initialState);
What its wrong? 怎么了?
Although I fail to completely understand the intent of the OP here, following is my take on the question 虽然我在这里未能完全理解OP的意图,但以下是我对这个问题的看法
_myCart
can be a local variable because it doesn't seem to serve any greater purpose, atleast from the code provided by OP _myCart
可以是局部变量,因为它似乎没有任何更大的目的,至少从OP提供的代码
The call to instance.init
can be with empty parenthesis or with a legitimate variable- depends on what OP is trying to achieve here. 对instance.init
的调用可以是空括号或合法变量 - 取决于OP在这里尝试实现的内容。
I've included both main.js code snippet as well as testVariable.instance.init();
我已经包含了main.js代码片段以及testVariable.instance.init();
(on a simple note its undefined if it is undefined anyway as commented by @Bergi) (简单来说,如果@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.