http服务器在nodejs jest测试中未定义

ru9i0ody  于 2023-03-10  发布在  Jest
关注(0)|答案(2)|浏览(187)

我正在学习用jest进行nodejs测试,我的设置如下。

|-tsconfig.json
|-package.json
|-src
     |-mytest.spec.ts

tsconfig.json

{
  "compilerOptions": {
    "module": "NodeNext",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": true,
    "noImplicitAny": true,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false
  }
}

package.json

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "author": "",
  "private": true,
  "license": "",
  "scripts": {
    "test": "jest"
  },
  "dependencies": {},
  "devDependencies": {
    "@types/jest": "28.1.8",
    "@types/node": "^16.0.0",
    "jest": "28.1.3",
    "supertest": "^6.1.3",
    "ts-jest": "28.0.8",
    "typescript": "^4.7.4"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
}

mytest.spec.ts

import http from 'http';

describe('My HTTP server', () => {
  let server: http.Server;

  beforeAll(() => {
    // Start the server
    console.log(http);
    server = http.createServer((req, res) => {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
      res.end('Hello, World!');
    });
    server.listen(3000);
    // Return the server instance
    return server;
  });

  afterAll(() => {
    // Stop the server
    server.close();
  });

  test('responds with "Hello, World!"', async () => {
    // Make a request to the server
    const response = await new Promise<http.IncomingMessage>(
      (resolve, reject) => {
        http.get('http://localhost:3000', resolve);
      },
    );

    // Check the response
    expect(response.statusCode).toBe(200);
    expect(response.headers['content-type']).toBe('text/plain');
    expect(await readBody(response)).toBe('Hello, World!');
  });

  test('server is listening on port 3000', () => {
    // Check if the server is listening
    expect(server.listening).toBe(true);
  });
});

// Helper function to read the response body
async function readBody(response: http.IncomingMessage): Promise<string> {
  const chunks: Uint8Array[] = [];
  for await (const chunk of response) {
    chunks.push(chunk);
  }
  return Buffer.concat(chunks).toString('utf8');
}

每当我运行npm时运行jest。我得到以下错误
TypeError:无法读取未定义的属性(阅读“createServer”)
以及
TypeError:无法读取未定义的属性(阅读“close”)
谁能给我指个路吗?http不是node的一部分吗?

ttygqcqt

ttygqcqt1#

const http=require('http');


const server=http.createServer((req,res)=>{

// Your logic will written here

      
});

server. Listen(3000);

必须将http.createServer方法存储在某个变量中。

yjghlzjz

yjghlzjz2#

我最终通过添加**“esModuleInterop”解决了这个问题:true**到我的tsconfig.json文件中,显然这使得typeScript能够生成使用require加载CommonJS模块的代码,然后将默认的export赋值给import语句。

相关问题