如何为RequireJS项目编写单元测试

时间:2018-03-08 07:08:35

标签: javascript unit-testing typescript requirejs mocha

我正在尝试用chai mocha编写单元测试,但收到以下错误。

  

ReferenceError:未定义define

此应用程序是用TypeScript编写的,如果我尝试创建一些虚拟文件来创建单元测试,它可以正常工作而无需任何导入。

单元测试代码在

之下
import { expect } from 'chai';
import { MarionetteApp } from '../app/app';

describe("MarionetteApp", () => {
    describe("Add", () => {
        it("Should return 3 when a = 1 and b = 2", () => {
            let calc = new MarionetteApp();

            var result = calc.test();

            expect(result).to.equal("hello");
        });
    });
});

我想要编写单元测试的文件是

import { RootView } from './views/RootView';
import { AdvancedCustomController } from './controllers/AdvancedCustomController';
import * as DB from './db/DB';


export class MarionetteApp extends Marionette.Application {

    constructor() {
        super();
    }

    test(){
        return "hello";
    }

    initialize() {
        (<any>window).UXToolApp = this;
    }

    onBeforeStart() {
        //Init controllers
        var advancedCustomizationController = new AdvancedCustomController();

        //Init views
        var rootView = new RootView();
        rootView.render();
    }

}

在运行单元测试时,我收到了以下错误

error image

tsconfig文件如下:

 "version": "1.5.0-beta",
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true,
        // "module": "commonjs",
        "isolatedModules": true,
        "jsx": "react",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "declaration": true,
        "noImplicitAny": false,
        "removeComments": false,
        "noLib": false,
        "preserveConstEnums": true,
        "suppressImplicitAnyIndexErrors": true,
        "rootDir": "./app",
        "moduleResolution" : "node"
    },

并且package.json是下面的

{
  "name": "design_mode",
  "version": "1.0.0",
  "description": "",
  "main": "scripts/designMode.ts",
  "directories": {
    "test": "test"
  },
  "dependencies": {
    "amd-loader": "^0.0.8",
    "amdefine": "^1.0.1",
    "chai": "^4.1.2",
    "mocha": "^5.0.3",
    "requirejs": "^2.3.5",
    "ts-node": "^5.0.1",
    "ws": "^0.4.32"
  },
  "devDependencies": {
    "del": "^2.0.0",
    "gulp": "^3.9.0",
    "gulp-less": "^3.0.3",
    "gulp-rename": "^1.2.2",
    "gulp-sourcemaps": "^1.6.0",
    "gulp-tslint": "^3.2.0",
    "gulp-typescript": "^2.8.1",
    "gulp-util": "^3.0.6",
    "less": "^2.5.1",
    "tsd": "^0.6.4",
    "typescript": "^2.7.2"
  },
  "scripts": {
    "test": "./node_modules/.bin/mocha --compilers ts:ts-node/register ./test/*.spec.ts",
    "server": "cd server && node server.js",
    "build": "gulp"
  },
  "author": "",
  "license": "ISC"
}

1 个答案:

答案 0 :(得分:0)

转到项目根目录,然后 安装amd-loader模块并尝试在以下命令下运行,此问题将得到解决。

node node_modules/mocha/bin/mocha --require ts-node/register -r amd-loader --timeout=0 tests/**/*.ts