I am using the jsonapi-serializer library to deserialize API data. I promisified the callback using angular's $q constructor and wrapped that in a service, this works fine on the browser, but when I test it using jasmine on the karma runner, the promise doesn't resolve. This is the method on the service (Notice I'm using TypeScript)
public deserialize(type: string, data: any): any {
// get the predefined options for resource type
let deserializeOpts: any = this.deserializeOpts[type];
// use jsonapi-serializer
// the options are not working
let deserializer: any = new JAS.Deserializer({});
console.log(data);
// return a promise with the parsed object
return this._$q((resolve: any, reject: any) => {
deserializer.deserialize(data, (err: any, result: any) => {
if (result) {
console.log(resolve);
resolve(result);
} else {
console.log(err);
reject(err);
}
});
});
}
This is my test after a while trying to debug it
it('should flatten jsonapi user', function (done) {
var deserialized;
JsonapiParser.deserialize(type, apiUser).then(
(result) => {
deserialized = result;
expect(deserialized).toEqual(apiUser);
done();
}
);
});
An this is a sample use of the mentioned deserializer service
// returns the promise so controller can display the errors
return this.$http.get(url)
.then(
(response: any) => {
if (response.data.data.length !== 0) {// deserialize data
return this._deserializer.deserialize('activities', response.data) // the deserializer service is called;
} else { // throw an error if data is empty
return this.$q.reject({ error: this.ACTIVITY.empty });
}
},
() => {
return this.$q.reject({ error: this.ACTIVITY.connectionError });
}
).then(
(deserialized: any) => { // data is copied to original list so it doesn't lose it's bindings
angular.copy(deserialized, this.list); // the result from the deserializer is used
console.log(deserialized);
return this.list;
});
This last block of code works fine when compiled and run on the browser. But the tests get timed out. If I log inside the deserialize
method, I can see that the callback gets resolved, but the promise never seems to digest. If I place a $rootScope.$digest() after the call to resolve, the test works, but I don't want to hardcode that in there, especially since the code is working when deployed.