Utilizing the jsonapi-serializer library for deserializing API data, I have promisified the callback using angular's $q constructor and encapsulated it in a service. The functionality works as expected in the browser, however, when testing it with jasmine on the karma runner, the promise fails to resolve. Below is the TypeScript method implemented in the service:
public deserialize(type: string, data: any): any {
// fetch predefined options for resource type
let deserializeOpts: any = this.deserializeOpts[type];
// utilize jsonapi-serializer
// encountering issues with the options
let deserializer: any = new JAS.Deserializer({});
console.log(data);
// return a promise containing resolved 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 snippet showcases my debugging efforts during testing:
it('should flatten jsonapi user', function (done) {
var deserialized;
JsonapiParser.deserialize(type, apiUser).then(
(result) => {
deserialized = result;
expect(deserialized).toEqual(apiUser);
done();
}
);
});
Here is an example of how the deserializer service is utilized:
// returns the promise so controller can display errors
return this.$http.get(url)
.then(
(response: any) => {
if (response.data.data.length !== 0) {// deserialize data
return this._deserializer.deserialize('activities', response.data) // calling the deserializer service;
} else { // throw error if data is empty
return this.$q.reject({ error: this.ACTIVITY.empty });
}
},
() => {
return this.$q.reject({ error: this.ACTIVITY.connectionError });
}
).then(
(deserialized: any) => { // copy data back to original list to preserve bindings
angular.copy(deserialized, this.list); // utilizing results from deserializer
console.log(deserialized);
return this.list;
});
The above code functions properly when compiled and executed in the browser. However, the tests are timing out. Upon logging inside the deserialize
method, I observed that the callback is being resolved, but the promise does not seem to digest. Adding $rootScope.$digest() after the resolve call resolves the test issue, but hardcoding it is not ideal especially since the deployed code operates effectively.