运行Karma时使用sinon.spy测试全局函数(例如parseInt)抛出错误

时间:2018-10-10 17:39:03

标签: javascript typescript sinon karma-webpack

我在监视parseInt在函数中运行的频率时遇到了一些麻烦。这是我公司的Typescript集成的PoC。

我已经按照两个单独的指南来测试Sinon,但是没有一个指南提到使用global名称空间中的函数。

此外,除this one以外,我还没有发现关于在全局函数上使用spy的主题的任何帖子。

将鼠标悬停在spy函数(sinon.spy(global, "parseInt"))上也表明parseInt绝对是TypeScript中全局对象/名称空间的一部分

我收到此错误,它表示测试文件中不存在以下行:

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"
  }

删除所有行,但设置spy的那一行使测试运行正常。


PoC测试:

    /**
     * @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);
        }); 
    }); 

业力绞刑:

/*
    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
    })
}

1 个答案:

答案 0 :(得分:0)

我认为您可以在断言尝试之前恢复间谍活动:

sinon.assert.calledOnce(parseIntSpy);
parseIntSpy.restore();