0

I'm having some trouble with spying on how often parseInt is run in my function. This is a PoC for my company's Typescript integration

I've followed two separate guides on testing Sinon, but none of them have mentioned working with functions from the global namespace.

Further, I haven't found any posts regarding the subject of using spy on global functions except this one, which suggests it works..

Hovering over the spy function (sinon.spy(global, "parseInt")) also suggests that parseInt definitely is part of the global object / namespace in TypeScript

I'm getting this error which refers to a line that doesn't exist 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"
  }

Removing all the lines but the one setting up the spy makes the test run fine.


The PoC 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 scafolding:

/*
    KarmaJS defintion 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
    })
}
geostocker
  • 1,190
  • 2
  • 17
  • 29

1 Answers1

0

I think you are restoring the spy before the assertion try:

sinon.assert.calledOnce(parseIntSpy);
parseIntSpy.restore(); 
rc_dz
  • 461
  • 4
  • 20