Node.js 找不到名称";模块";
我正在尝试运行一个简单的typescript文件,其中导出一个名为Node.js 找不到名称";模块";,node.js,unit-testing,typescript,mocha.js,chai,Node.js,Unit Testing,Typescript,Mocha.js,Chai,我正在尝试运行一个简单的typescript文件,其中导出一个名为sum的函数,如下所示: 我正在编写节点脚本 function sum(a:number):number{ return a; } module.exports.sum=sum; 我不明白我做错了什么 我编写这个简单的脚本是为了理解单元测试用例。我想如果这个文件运行正常,那么我将使用mocha和chai启动基本测试用例 下面是我的测试代码: "use strict" // Import chai. let chai = r
sum
的函数,如下所示:
我正在编写节点脚本
function sum(a:number):number{
return a;
}
module.exports.sum=sum;
我不明白我做错了什么
我编写这个简单的脚本是为了理解单元测试用例。我想如果这个文件运行正常,那么我将使用mocha和chai启动基本测试用例
下面是我的测试代码:
"use strict"
// Import chai.
let chai = require('chai'),
path = require('path');
chai.should();
let SampleTest = require(path.join(__dirname, '..', 'sample.js'));
describe('Sampletesting', () => {
describe('function sum', function(){
it('should return number', function(){
sum(1).should.equal(1);
})
})
});
这种代码的平静对我来说很好 假设我们有一个名为
math_utils.ts
的模块,它导出一个名为foo
的函数和一个名为obj
// typescript syntax for exporting
export function foo(a: number): number {
// whatever
}
export const obj = { life: 42 }
const _aPrivateObjectToTheModule = {}
function _aPrivateFunctionToTheModule() {}
现在,我们在同一文件夹中定义另一个文件,例如math_utils.spec.ts
,它将导入我们的模块
import { should } from 'chai'
import { foo } from './math_utils'
// now we are able to call math_utils.foo()
describe('foo', () => {
it('should....', () => {
foo(1).should.equal(1);
})
})
现在,为了总结,在typescript中,您可以通过这种方式导入模块成员。。。或按如下方式导入整个模块:
import * as chai from 'chai'
import * as MathUtils from './math_utils'
// now in an object called MathUtils we have every member defined with the keyword export
const should = chai.should
describe('foo', () => {
it('should....', () => {
MathUtils.foo(1).should.equal(1);
})
})
describe('obj', ()=> {
// ...
MathUtils.obj
})
你能补充一下你是如何从外部导入它的吗?@Manu请找到我更新的代码,我在import*中用mocha和chaihere做了简单的测试,“/math_utils”的“MathUtils”指的是什么?我已经破解了你为什么在那里使用MathUtils,但当我运行我的测试时,我得到了另一个错误“意外保留字”并指向“导入”似乎与您的配置有关……可能您忘记了与编译器选项有关的内容吗?我使用可视化代码(免费代码),并且在项目根目录中始终需要一个名为
tsconfig.json
的文件。