【问题标题】:Typescript import module.exports sub functionTypescript 导入 module.exports 子函数
【发布时间】:2021-12-07 06:53:12
【问题描述】:

我正在使用 mocha 测试函数,但在运行测试文件时遇到错误。

文件结构如下

server
|-test
|  |-customer.test.ts
|-customer.js

这是customer.js文件函数

module.exports = (instance) => {
   instance.validate = async (ctx) => {
      // some code here 
   }
}

这是 mocha 测试用例文件 customer.test.ts

const instance =  require("../customer")

/* eslint-disable no-undef */
describe('customer', () => {
  describe('/POST customers', () => {
    it('Create Buy customer', (done) => {
      instance.validate({        
      })
      done();

    });
  })
});

但是当我使用命令mocha .\customer.test.ts 运行文件时,它会显示以下错误

TypeError: instance.validate is not a function

如何让上面的函数执行?

【问题讨论】:

    标签: node.js typescript mocha.js


    【解决方案1】:

    您正在导出的内容与您正在执行的导入内容不匹配。问题(可能)是出口。你拥有的是这样的:

    module.exports = (instance) => {
       instance.validate = async (ctx) => {
          // some code here 
       }
    }
    

    导出一个函数,在调用该函数时,会将validate 方法添加到您传递给它的对象。它确实使用validate 方法导出对象,如下所示:

    module.exports = {
       validate: async (ctx) => {
          // some code here 
       },
    };
    

    因此,您需要修复导出(我怀疑这是问题所在),或者(如果导出确实是为了这样做),通过传入一个对象然后检查它的实际作用,在调用,对象有一个validate方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-20
      • 2016-05-25
      • 2016-03-20
      • 2021-06-10
      • 1970-01-01
      • 2020-11-27
      • 2019-09-03
      相关资源
      最近更新 更多