我正在使用Jasmine 2.8和jasmine-ajax插件模拟jQuery getJSON调用。回调应该将数据存储回对象中。我有一个类结构如下。
// --------- settings.js ------------
class settings{
load(filename, callback){
let self = this;
$.getJSON(filename,funciton(d){
let err = false;
self._d = d;
callback(d, err);
}).fail(function(jqxhr, stat, err){
let msg = ... build error message ...
callback(msg, true);
});
}
}
// ------- myModule.js --------------
var Settings = require('settings');
class myModule{
constructor(settingsFile){
this._d = {};
this._file = settingsFile;
this._settings = new Settings();
}
load(callback){
let self = this;
this._settings.load(this._file, function(d,err){
if(!err){
self._d = d;
console.log(self._d); // prints the object
callback('success');
}
});
}
}
// ---------- myModuleSpec.js -------------
describe('manipulating data data', function(){
beforeEach(function(){
this.d = { pro1:'property1', prop2:{ foo:'bar' }};
jasmine.Ajax.install();
this.my = new MyModule('myfile.json');
this.cb = new jasmine.createSpy();
this.my.load(this.cb);
let r = jasmine.Ajax.requests.mostRecent();
r.respondWith({
status:200,
responseText.JSON.stringify(this.d);
});
});
afterEach(function(){
this.my = undefined;
jasmine.Ajax.uninstall();
});
it('should have called the callback',function(){
expect(this.cb).toHaveBeenCalled(); //passes
});
it('should contain the data', function(){
console.log(this.my._d); // prints { } to the console
expect(this.my._d).toEqual(jasmine.objectContaining(this.d)); // FAIL
});
});
Jasmine返回错误消息: 预期({})等于。
将print语句放入代码中会验证回调是否已被调用并收到但是在运行测试时,data属性(_d)是一个空对象。
我在nodejs中的命令行上使用jasmine。我有一个助手,使用JSDOM加载虚拟dom并配置global.getJasmineRequireObj来配置jaxmine-ajax;
谢谢。