简体   繁体   中英

jest/ts/ tests Cannot find name 'x'

I've read a ton of the previous SO questions regarding this however, none seems to solve any of my problems.

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'...
  });
});

I have installed both jest and mocha types, just to make sure that it wasn't registering one over the other. Pretty much everything is not being recognized, .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"]
}

server

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

I don't know what other information is relevant if there is something else I am missing I will update this with the information

You are exporting the named variable server directly while you are trying to import it as if it were the default export.

Just change it to import { server } from './server'; in index.test.ts and it will work as expected. You can also change the export to export default server in server.ts but I tend to avoid that based on this article .

Read more about export on MDN .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM