首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用sinon.spy测试运行Karma时的全局函数(如parseInt)抛出错误

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

Stack Overflow用户
提问于 2018-10-10 17:39:03
回答 1查看 713关注 0票数 0

在监视parseInt在我的函数中运行的频率方面,我遇到了一些麻烦。这是一个PoC,用于我公司的打字稿集成

我遵循了关于测试Sinon的两个单独指南,但没有提到使用global命名空间中的函数。

此外,我还没有找到任何关于在全局函数上使用spy这一主题的帖子,除了this one,这表明它可以工作。

悬停在spy函数(sinon.spy(global, "parseInt"))上也表明parseInt肯定是TypeScript中全局对象/命名空间的一部分。

我得到了这个错误,它引用了测试文件中不存在的一行:

代码语言:javascript
复制
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测试:

代码语言:javascript
复制
    /**
     * @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脚手架:

代码语言:javascript
复制
/*
    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
    })
}
EN

回答 1

Stack Overflow用户

发布于 2018-10-10 20:41:46

我认为在断言尝试之前,你是在恢复间谍:

代码语言:javascript
复制
sinon.assert.calledOnce(parseIntSpy);
parseIntSpy.restore(); 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52745925

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档