【问题标题】:Using sinon.spy to test global functions (such as parseInt) throwing error when running Karma使用 sinon.spy 测试全局函数(如 parseInt)在运行 Karma 时抛出错误
【发布时间】:2018-10-10 17:39:03
【问题描述】:

我在监视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
    })
}

【问题讨论】:

    标签: javascript typescript sinon karma-webpack


    【解决方案1】:

    我认为您在断言尝试之前正在恢复间谍:

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

    【讨论】:

      猜你喜欢
      • 2016-06-24
      • 1970-01-01
      • 2016-08-08
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多