I'm currently facing an issue with monitoring the usage of parseInt
within my function. This is a Proof of Concept for integrating TypeScript into our company's workflow.
I've tried following two different tutorials on testing Sinon, but none of them touch upon dealing with functions from the global
namespace.
Moreover, I haven't come across any discussions regarding utilizing spy
on global functions except for this particular thread, which implies that it can be done.
Upon hovering over the spy
function (sinon.spy(global, "parseInt")
), it becomes evident that parseInt
indeed belongs to the global object / namespace in TypeScript.
I have encountered this error that points to a non-existent line in the test file:
PhantomJS 2.1.1 (Windows 8 0.0.0) ERROR
{
"message": "SyntaxError: Unexpected token '>'\nat scripts/fortress/typescript/tests/dependencies/func.spec.ts:119:0",
"str": "SyntaxError: Unexpected token '>'\nat scripts/fortress/typescript/tests/dependencies/func.spec.ts:119:0"
}
When I strip away all lines except for the one where the spy
is set up, the test runs smoothly.
The Proof of Concept test:
/**
* @description Takes two parameters and determines if they are of the same type.
* @param {string} property A Date string (example: 'Date(1231231311231)')
* @returns {number} A number indicating the time from epoch.
*/
export class Functions {
getDateNumberFromJsonPropertyString(property : string) : number {
return parseInt(property.substring(property.indexOf("(") + 1, property.indexOf(")")));
}
}
describe("GetdateNumberFromJsonPropertyString", function() {
it("should call parseInt once", function() {
let parseIntSpy = sinon.spy(global, "parseInt"); // <-- Breaks here
func.getDateNumberFromJsonPropertyString("(1)");
parseIntSpy.restore();
sinon.assert.calledOnce(parseIntSpy);
});
});
Karma scaffolding:
/*
KarmaJS definition file for all required unit tests.
*/
let webpackConfig = require('./webpack.config');
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai', 'sinon'],
files: [
"scripts/fortress/typescript/tests/**/*.ts"
],
exclude: [
"node_modules/"
],
preprocessors: {
"scripts/fortress/typescript/tests/**/*.ts" : ["webpack"]
},
webpack: {
mode: "development",
module: webpackConfig.module,
resolve: webpackConfig.resolve
},
reporters: ["progress"],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ["PhantomJS"],
singleRun: false,
concurrency: Infinity
})
}