TypeScript:为什么Map键迭代不会发生?

时间:2017-11-10 13:16:19

标签: typescript karma-jasmine

TypeScript,Karma,Jasmine,WebStorm。

我在WebStorm IDE中构建,调试和解决了我的代码。

简单的测试类(针对问题显示):

export class Foo{

    readonly books : Map<string,number>;

    constructor(){
        this.books = new Map<string,number>();
    }
}

简单测试:

import 'jasmine';
import {Foo} from "../src/entry";

describe('#Foo class.',()=>{

    it('Check the `book` map keys iteration.',()=>{
        const foo = new Foo();
        foo.books.set('Book 1', 5);
        foo.books.set('Book 2', 7);
        foo.books.set('Book 3', 6);

        let count = 0;

        for(let n of foo.books.keys()){
            ++count; // Here is some code. Hm... I wasn't here!
        }
        expect(count).toBe(foo.books.size); // Report: Expected 0 to be 3.
    });
});

此测试失败。评论显示原因。

enter image description here

我也看到Karma服务器写入控制台:

  

错误[compiler.karma-typescript]:   node_modules/@types/bluebird/index.d.ts(660,33):错误TS2304:不能   找到名称&#39; Map&#39;。

嗯...我安装了bluebird@types/bluebird,但它没有帮助。因此我将它们卸回了。

为什么迭代不会发生?我该如何解决?

有我的配置文件:

的package.json

{
  "name": "karma-for-typescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack",
    "test": "jasmine"
  },
  "keywords": [],
  "author": "Andrey Bushman <bushman.andrey@gmail.com> (https://github.com/Andrey-Bushman/)",
  "license": "ISC",
  "devDependencies": {
    "@types/jasmine": "^2.6.3",
    "@types/karma": "^1.7.2",
    "@types/karma-coverage": "^0.5.33",
    "@types/karma-jasmine": "0.0.29",
    "jasmine": "^2.8.0",
    "jasmine-core": "^2.8.0",
    "jasmine-spec-reporter": "^4.2.1",
    "jasmine-ts": "^0.2.1",
    "karma": "^1.7.1",
    "karma-chrome-launcher": "^2.2.0",
    "karma-growl-reporter": "^1.0.0",
    "karma-html-reporter": "^0.2.7",
    "karma-jasmine": "^1.1.0",
    "karma-typescript": "^3.0.8",
    "karma-typescript-es6-transform": "^1.0.2",
    "karma-typescript-preprocessor": "^0.3.1",
    "progress": "^2.0.0",
    "ts-loader": "^3.1.1",
    "typescript": "^2.6.1",
    "webpack": "^3.8.1"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es6",
    "allowJs": true,
    "baseUrl": "types"
  }
}

webpack.config.js

'use strict';

var path = require('path');

module.exports = {
  entry: {
    api: './src/entry.ts'
  },
  devtool: 'inline-source-map',
  module: {
    rules: [{
      test: /\.tsx?$/,
      use: 'ts-loader',
      exclude: /node_modules/
    }]
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"]
  },
  output: {
    filename: 'module.js',
    path: path.resolve(__dirname, 'dist')
  }
};

karma.conf.ts

module.exports = (config : any) =>{
    config.set({
        karmaTypescriptConfig: {
            bundlerOptions: {
                transforms: [require("karma-typescript-es6-transform")()]
            }
        },
        // the default configuration
        htmlReporter: {
            outputDir: 'dist/unit_testing', // where to put the reports
            templatePath: null, // set if you moved jasmine_template.html
            focusOnFailures: true, // reports show failures on start
            namedFiles: false, // name files instead of creating sub-directories
            pageTitle: null, // page title for reports; browser info by default
            urlFriendlyName: false, // simply replaces spaces with _ for files/dirs
            reportName: 'summary_report', // report summary filename; browser info by default

            // experimental
            preserveDescribeNesting: false, // folded suites stay folded
            foldAll: false, // reports start folded (only with preserveDescribeNesting)
        },

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine', "karma-typescript"],

        // list of files / patterns to load in the browser
        files: [
            {pattern: "src/**/*.ts"}, {pattern: "test/**/*.ts"}
        ],

        // list of files to exclude
        exclude: [
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            "src/**/*.ts": ["karma-typescript", "coverage"],
            '**/*.ts': ["karma-typescript"]
        },

        reporters: ['progress', 'karma-typescript', 'html'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity
    })
}

Here是此示例的代码源。

1 个答案:

答案 0 :(得分:0)

将您的Foo.test.ts脚本更改为:

import 'jasmine';
import {Foo} from "../src/entry";

describe('#Foo class.',()=>{

    it('Check the `book` map keys iteration.',()=>{
        const foo = new Foo();
        foo.books.set('Book 1', 5);
        foo.books.set('Book 2', 7);
        foo.books.set('Book 3', 6);

        let count = 0;

        foo.books.forEach((value: number, key: string ) => {
            console.log(key, value);
            ++count;
        });
        expect(count).toBe(foo.books.size); // Report: Expected 0 to be 3.
    });
});

我将for循环更改为forEach,以便能够迭代到Map中。

enter image description here