My current challenge involves testing a utility class that contains static methods using jasmine and typescript. The issue arises from the fact that this helper class relies on a 3rd party library to accomplish a particular task. I must validate that this 3rd party library is invoked in all scenarios.
import Helpers from '../../src/utils/Helpers';
import {parseString} from 'xml2js';
describe('Helper class', function() {
let mockParseString: any;
describe('xmlToJson', function() {
beforeEach(function(done) {
mockParseString = jasmine.createSpy('parseString', parseString);
// spyOn(xml2js, 'parseString').and.callFake(function(xml: string, callback: (error: any, data: object) => void) {
//
// });
setTimeout(() => {
done();
}, 1);
})
it('calls library to parse string', async function(done) {
await Helpers.xmlToJson('<div></div>');
expect(mockParseString).toHaveBeenCalled();
done();
})
})
});
Within the helper class, I am simply encapsulating a callback function within a promise:
import {convertableToString, OptionsV2, parseString} from 'xml2js';
export default class Helpers {
public static xmlToJson(xml: convertableToString, options?: OptionsV2): Promise<any> {
return new Promise((resolve, reject) => {
if(options) {
parseString(xml, (err, results) => {
if(err) {
reject(err);
}
resolve(results);
});
} else {
parseString(xml, options, (err, results) => {
if(err) {
reject(err);
}
resolve(results);
});
}
})
}
}
Unfortunately, I have encountered an error indicating that the spy is not being triggered. Despite my efforts, I have been unable to find a solution to make the spy function as expected. It's possible that this limitation may be unavoidable.
EDIT
This is how I am executing the test:
./node_modules/.bin/ts-node ./node_modules/.bin/jasmine spec/utils/Helpers-spec.ts