node.js - 找不到名称 "module"

标签 node.js unit-testing typescript mocha.js chai

我正在尝试运行一个简单的 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/

相关文章:

javascript - TypeScript:如何为代理对象上的值创建类型?

typescript - 如何在 TypeScript 中限制为只有 2 个数字索引签名类

node.js - 如何在 Node 中对 Stripe Connect 访问 token 发出 POST 请求?

python - Django Rest Framework 中的 APITestCase、APISImpleTestCase 和 APITransactionTestCase 有哪些不同的用例

c# - 使用 Moq 实例引发 EventHandler<TEventArgs> 事件

c# - Asp.Net Core 2.1 ApiController 不会自动验证单元测试下的模型

node.js - 如何快速执行终端命令?

node.js - Node.js 中的 PayPal 自适应支付问题

node.js - 将 cookieSession 与 Passport 一起使用

typescript - CDK Step Functions - 如何创建循环