我正在尝试测试一个简单的对象并跟踪其自己的方法更改的属性。不知怎的,启动方法后属性的值没有改变:
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
});
我已经看到一些关于使用 getter 和 setter 而不是对象文字,然后使用 spy OnProperty 的提示,但我不知道在尝试保持 newCar.climatronicOn() 和 newCar 的形式时如何构建和运行它.climatronicOff()。如何检查方法是否更新父对象属性?
package.json 中的我的 devDependency:
"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"
最佳答案
当您spyOn
一个函数(例如startClimatronic
),然后调用该函数(例如newCar.startClimatronic();
)时,您并没有调用它的实际实现,而是调用一个 stub 的jasmine
。因此,为了使测试成功,您需要在 spy
上调用 .and.callThrough();
。类似的东西
spyOn(newCar, 'startClimatronic').and.callThrough();
spyOn(newCar, 'stopClimatronic').and.callThrough();
因此,运行测试已成功完成。
希望对你有帮助
关于javascript - 使用 karma-jasmine 测试规范内的对象属性更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51369666/