0

我有以下简单的代码

import app from '../src/app';
import * as chai from 'chai';
import chaiHttp = require('chai-http');

chai.use(chaiHttp);
const expect = chai.expect;

describe('Get /', () => {
    it('Should say hi there', async () => {
        const response = chai.request(app).get('/');
        console.log(response);
        expect(5).to.equal(5);
    });
});

每次我跑

mocha -r ts-node/register lib/tests/**/sample.spec.ts

我收到以下错误

TypeError:chai.request 不是函数

我用同样的问题查看了其他 stackoverflow 帖子。他们都说添加

chai.use(chaiHttp) 

应该解决问题

但是,正如你所看到的,我已经有了。

有任何想法吗?

4

2 回答 2

1
  1. 如果esModuleInteropfalse您的 中tsconfig.json,它应该可以正常工作。
import * as chai from 'chai';
import chaiHttp = require('chai-http');

chai.use(chaiHttp);
const expect = chai.expect;

describe('Get /', () => {
  it('Should say hi there', async () => {
    expect(chai.request).to.be.a('function');
  });
});

测试结果:

  Get /
    ✓ Should say hi there


  1 passing (4ms)
  1. 如果esModuleInteroptrue,你应该使用import chai from 'chai';而不是使用import * as chai from 'chai';
于 2020-12-24T10:18:57.287 回答
0

将 chai-http 与 chai 一起使用

const chai = require("chai");
const chaiHttp = require("chai-http");

那么 chai.use(chaiHttp); 这对我有用。

于 2021-03-17T13:32:00.070 回答