首页 > 解决方案 > 如何在 TypeScript Chai 中访问响应文本?

问题描述

在下面helloWorld.test.ts我无法访问res.text以测试 HTML 结果:

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

import app from '../src/App';

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

describe('baseRoute', () => {

  it('should be html', async () => {
    const res = await chai.request(app).get('/');
    expect(res.type).to.eql('text/html');
  });

  it('should have the message in body', async () => {
    const res = await chai.request(app).get('/');
    //console.log("Result:", res);
    expect(res.text).to.eql('<html><head><title>Hey</title></head><body><h1>Hello world!</h1></body></html>');
  });

});

当我尝试在 VSCode 中构建我的项目时,我收到一个Property 'text' does not exist on type 'Response'.错误,这与仅显示 a 的三个属性的自动完成一致Responsebody、、statustype

res.body总是{}如此,根据对以下问题的回答,应该使用(res.text在 JavaScript 中):Chai response.body 始终为空 {}

如何在 TypeScript 中访问res.text

标签: typescriptchai

解决方案


就我而言,我已经@types/chai-http安装了(来自旧教程),但https://www.npmjs.com/package/@types/chai-http说它已被弃用。我假设在 TypeScript 中它是一个非常有限的 API,因为版本是 0.0.23(或其他版本)。

npm uninstall @types/chai-http打开所有属性的自动完成功能,包括.text. 这解决了我的问题。


推荐阅读