网站搜索

node.js - jest/ts/ 测试 找不到名称 'x'


我已经阅读了大量之前关于这个问题的 SO 问题,但似乎没有一个能解决我的任何问题。

index.test.ts

import request from 'supertest';
import * as server from '../server';
import 'jest'

//close server after each request
afterEach( //cannot find name 'afterEach'
  async (): Promise<void> => {
    await server.close(); // Property 'close' does not exist on type 'typeof import(<path to file)'
  },
);

describe('get /', (): void => { //Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`
  it('should respond as expected', async (): Promise<void> => {// cannot find 'it'...
    const response = await request(server).get('/');
    expect(response.status).toEqual(200); // cannot find 'expect'
    expect(response.body.data).toEqual('Sending some JSON'); // cannot find 'expect'...
  });
});

我已经安装了 jest 和 mocha 的类型,只是为了确保它们不会相互覆盖。几乎所有的东西都无法被识别,.babelrc

{
  "presets": ["@babel/preset-typescript"]
}

jest.config.js

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
};

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "noImplicitAny": true,
    "preserveConstEnums": true,
    "outDir": "./dist",
    "sourceMap": true,
    "esModuleInterop": true
  },
  "include": ["./src/**/*"],
  "exclude": ["test", "**/*/spec.ts", "**/*/test.ts"]
}

服务器

import * as dotenv from 'dotenv';
dotenv.config();
import Koa from 'koa';
import logger from 'koa-logger';
import apiRoutes from './Routes';
import cors from '@koa/cors';
import bodyParser from 'koa-bodyparser';
const app = new Koa();
const PORT = process.env.PORT || 3001;
const ENV = process.env.NODE_ENV || 'Development';

app.use(logger());
app.use(cors());
app.use(bodyParser());
app.use(apiRoutes);

export const server = app.listen(PORT, (): void => {
  console.log(`🌍 Server listening on port ${PORT} - ${ENV} environment`);
});

我不知道还有哪些其他信息是相关的,如果我遗漏了什么,我会用这些信息来更新此内容

答案#1

你正在直接导出名为 server 的变量,而你却试图像导入默认导出一样导入它。

只需在 index.test.ts 中将其更改为 import { server } from './server';,它就会按预期工作。你也可以在 server.ts 中将导出更改为 export default server,但我倾向于根据这篇文章避免这样做。

在 MDN 上阅读有关 export 的更多内容。