【问题标题】:Node Express Mocha test: TypeError: chai.request is not a functionNode Express Mocha 测试:TypeError: chai.request is not a function
【发布时间】:2019-02-08 00:57:40
【问题描述】:

我有一个 Typscript 应用程序和 API。我根据大量 Google 搜索以及在 SO 和其他地方找到的一些示例编写了以下测试。我在测试代码中看不到任何问题。谷歌搜索TypeError: chai.request is not a function,到目前为止,我现在在哪里。您在下面看到我的错误吗?

谢谢,谢谢,谢谢你的帮助:-)

【问题讨论】:

    标签: node.js typescript express mocha.js chai


    【解决方案1】:

    您正在混合 importrequire 语法,这是个坏主意!

    仅使用import 语法:

    import * as chai from 'chai';
    import * as chai-http from 'chai-http';
    
    chai.use(chai-http);
    

    编辑

    不幸的是,chai-http 似乎不支持 es6 模块语法。可以看问题here

    import * as chai from 'chai';
    import chaiHttp = require('chai-http');
    
    chai.use(chai-http);
    

    【讨论】:

    • 是的,我发现了模块导入问题。我发现了多种不同的加载和链接 chai/chai-http 的方式。杀死我的部分是没有人报告我的错误。至少我找不到它。所以这个问题非常模糊,我无法解决。谢谢你的回复:-)
    【解决方案2】:

    我通过以下方法解决了这个问题(Express.js with TypeScript)

    import chai from 'chai';
    import chaiHttp from 'chai-http';
    
    chai.use(chaiHttp);
    

    希望对你有帮助。

    记得安装 @types/chai 和其他类型定义包让上面的块工作

    【讨论】:

    • 我错过了那个。谢谢!
    【解决方案3】:

    从 github 安装

    "devDependencies": {
        "chai-http": "git+https://github.com/chaijs/chai-http.git",
      },
    

    【讨论】:

      【解决方案4】:

      非常感谢您的回复!最终,我不得不更改 chai.request 的导入位置/方式并重写测试。根据测试中的代码,您可能认为前 5 行中的 1 行或更多行是不必要的,但它们全部都是。假设rest api是在3000上启动的,下面的代码可以运行,测试通过。

      我是否正确编写了这个 api 请求测试?我刚刚在学习 Mocha/Chai,所以它可能是错误的......

      import * as chai from 'chai';
      import chaiHttp = require('chai-http');
      chai.use(chaiHttp);
      import { Response } from 'superagent';
      import { request, expect } from 'chai';
      
      describe('AppController', () => {
          describe('Route GET /app', () => {
              it('Should GET to /app', async () => {
                  const res: Response = await request('http://0.0.0.0:3000').get('/app');
                  expect(res).to.have.status(200);
                  expect(res).to.be.a('object');
              });
          });
      
      });
      

      【讨论】:

      • 对我来说看起来不错。 ? 也许,我们可以通过检查实际响应值来改进代码,而不仅仅是object
      【解决方案5】:

      我可以在我自己的机器上重现该问题。这就是我解决它的方法。

      import * as chai from 'chai';
      import chaiHttp = require('chai-http');
      
      chai.use(chaiHttp);
      

      我还需要安装 @types/chai-http 以便编译器知道。

      npm install @types/chai-http --save-dev
      

      希望对你有帮助

      【讨论】:

      • 我收到错误 - TypeError: chai.request is not a function
      【解决方案6】:

      如果我启用esModuleInterop 编译器选项,我可以重现该问题。启用此选项后,import * as chai from 'chai'; 仅导入 chai 模块在导入时具有的成员。事实上,我认为在运行时将导出添加到 ES 模块被认为是不明智的。改用import chai from 'chai';import chai = require('chai');;任何一个都为我工作。

      【讨论】:

      • 你是救世主!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 1970-01-01
      • 2017-11-19
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      相关资源
      最近更新 更多