Reputation: 202
I'm trying to test a simple object and track its own properties changed by its own methods. Somehow the value of the property isn't changing after launching the methods:
it('extending an object with new properties', function() {
var newCar = Object.create(car);
newCar.climatronicOn = false;
newCar.startClimatronic = function(){
newCar.climatronicOn = true;
}
newCar.stopClimatronic = function(){
newCar.climatronicOn = false;
}
spyOn(newCar, 'startClimatronic');
spyOn(newCar, 'stopClimatronic');
// properties
expect(newCar.hasOwnProperty("climatronicOn")).toBeTruthy();
expect(typeof newCar.climatronicOn).toEqual("boolean");
// methods
expect(newCar.hasOwnProperty("startClimatronic")).toBeTruthy();
expect(typeof newCar.startClimatronic).toEqual("function");
expect(newCar.hasOwnProperty("stopClimatronic")).toBeTruthy();
expect(typeof newCar.stopClimatronic).toEqual("function");
// running methods
newCar.startClimatronic(); // should change the newCar.climatronicOn to true
expect(newCar.startClimatronic).toHaveBeenCalled(); // true
expect(newCar.climatronicOn).toBeTruthy(); // false, I expected true
});
I've seen some hints about using getters and setters instead of an object literal and then using spyOnProperty, but I have no idea how to make this up and running when trying to keep the form of newCar.climatronicOn() and newCar.climatronicOff(). How can I check if the methods update the parent objects properties?
My devDependencies from package.json:
"babel-polyfill": "^6.16.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-es2016": "^6.24.1",
"babel-preset-es2017": "^6.24.1",
"jasmine-core": "^2.5.2",
"karma": "^0.13.20",
"karma-babel-preprocessor": "^6.0.1",
"karma-chrome-launcher": "^0.2.2",
"karma-es6-shim": "^1.0.0",
"karma-firefox-launcher": "^0.1.7",
"karma-ie-launcher": "^0.2.0",
"karma-jasmine": "^0.3.7",
"karma-phantomjs-launcher": "^1.0.0",
"karma-spec-reporter": "0.0.26",
"phantomjs-prebuilt": "^2.1.3",
"run-sequence": "^1.2.2"
Upvotes: 0
Views: 2211
Reputation: 7803
When you spyOn
a function( e.g. startClimatronic
), and later you call that function(e.g. newCar.startClimatronic();
) you are not calling the actual implementation of it and instead of a stubbed jasmine
's. So, to make your test success, you need to call .and.callThrough();
on the spy
. Something like
spyOn(newCar, 'startClimatronic').and.callThrough();
spyOn(newCar, 'stopClimatronic').and.callThrough();
So, running your tests finished with all success.
Hope it helps
Upvotes: 2