[英]How to write unit test for a RequireJS project
I am trying to write unit tests with chai mocha, but getting the following error.我正在尝试使用 chai mocha 编写单元测试,但出现以下错误。
ReferenceError: define is not defined
ReferenceError:定义未定义
This application is written in TypeScript and if I tried to create some dummy file to create unit test, it works fine without having any import.此应用程序是用 TypeScript 编写的,如果我尝试创建一些虚拟文件来创建单元测试,它无需任何导入即可正常工作。
unit test code is below单元测试代码如下
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");
});
});
});
The file for which I want to write unit test is我要为其编写单元测试的文件是
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();
}
}
While running unit test, I am getting bellow error运行单元测试时,出现以下错误
tsconfig file is bellow 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"
},
and package.json is bellow 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"
}
Go to the project root directory and Install amd-loader module and try running below command, this issue will be resolved.转到项目根目录并安装 amd-loader 模块并尝试运行以下命令,此问题将得到解决。
node node_modules/mocha/bin/mocha --require ts-node/register -r amd-loader --timeout=0 tests/**/*.ts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.