我正在尝试运行一个简单的 typescript 文件,我正在导出一个名为 sum
的函数,如下所示:
我正在编写 Node 脚本。
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
})
关于node.js - 找不到名称 "module",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39438239/