关于此,我已经阅读了很多以前的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'...
});
});
我已经安装了笑话和摩卡两种类型,只是为了确保它没有在另一种上注册。几乎所有的东西都没有被承认, .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`);
});
如果我缺少其他信息,我不知道还有哪些其他信息有用,我将用信息更新此信息
答案 0 :(得分:1)
您在尝试导入命名变量server
时将其直接导出,就像它是默认导出一样。
只需将其更改为import { server } from './server';
中的index.test.ts
,即可正常使用。您也可以在export default server
中将导出更改为server.ts
,但我倾向于避免基于this article进行导出。
了解更多about export
on MDN。