【问题标题】:jest/ts/ tests Cannot find name 'x'jest/ts/tests 找不到名称“x”
【发布时间】:2019-08-27 20:13:27
【问题描述】:

我已经阅读了很多关于此的之前的 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 类型,只是为了确保它没有注册另一个。几乎所有东西都没有被识别, .babelrcc

{
  "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`);
});

我不知道还有哪些其他信息是相关的,如果我还缺少其他信息,我会用这些信息更新此信息

【问题讨论】:

  • “server”文件中的服务器是如何导出的?可能还需要查看server 的源内容。
  • 好的,我补充一下

标签: node.js typescript jestjs koa


【解决方案1】:

当您尝试像默认导出一样导入命名变量server 时,您正在直接导出它。

只需将index.test.ts 中的import { server } from './server'; 更改为index.test.ts,它就会按预期工作。您也可以在server.ts 中将导出更改为export default server,但我倾向于避免基于this article

阅读更多about export on MDN

【讨论】:

  • 非常感谢您的帮助!虽然我对前端的 TS 感觉很舒服,但后端以及使用 babel 和其他包/配置有时会有点棘手,尤其是在测试时。谢谢!
猜你喜欢
  • 2018-07-08
  • 2019-07-13
  • 2018-04-19
  • 1970-01-01
  • 2021-01-26
  • 2019-12-25
  • 2019-10-28
  • 2020-02-15
  • 1970-01-01
相关资源
最近更新 更多