2

我正在使用 Typescript 和 Nodejs 构建一个 API。所以我决定使用 Jest(也使用 ts-jest)和 Supertest 来创建一个单独的测试环境,该环境也使用不同的数据库,但我遇到了一个我无法修复的错误。错误说 Server 不是构造函数,但是当我运行应用程序时,它工作正常。这是代码和错误

服务器.ts

import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as mongoose from 'mongoose';
import { environment } from '../common/environment';
import { registerRoutes } from './routes';

export class Server {
    app: express.Express;
    router: express.Router;

    initDb(): Promise<any>{
        return mongoose.connect(environment.db.url, environment.db.options);
    }
    initRoutes(): Promise<any> {
        return new Promise((resolve, reject) => {
            try {
                this.app = express();
                this.app.set('port', environment.server.port);
                this.app.use(bodyParser.urlencoded({ extended: true }));
                this.app.use(bodyParser.json());
                registerRoutes(); // registra as rotas e os errorHandlers

                this.app.listen(this.app.get('port'), () => {
                    resolve();
                });

            } catch (err) {
                reject(err);
            }
        })
    }
    bootstrap(): Promise<Server> {
        return this.initDb().then(() =>
            this.initRoutes().then(() => this))
    }
}

这是创建服务器实例的模块

索引.ts

import { Server } from './server/server';

const server: Server = new Server();
server.bootstrap()
    .then(server => {
        console.log(`Server is listening on port: ${server.app.get('port')}`);
    }).catch(error => {
        console.log('Server failed to start');
        console.error(error);
        process.exit(1);
    });
export { server };

import { Server } from './server/server';

const server: Server = new Server();
server.bootstrap()
    .then(server => {
        console.log(`Server is listening on port: ${server.app.get('port')}`);
    }).catch(error => {
        console.log('Server failed to start');
        console.error(error);
        process.exit(1);
    });
export { server };

这是我正在尝试做的测试文件。我不明白的一件事是,当我删除下面的服务器实例并仅使用在 index.ts 处创建的实例时,错误消失了

users.test.ts

import 'jest';
import * as request from 'supertest';
import { Server } from '../server/server';
import { User } from './users-model';
import { usersRouter } from './users-config';
import { environment } from '../common/environment';

const url = 'http://localhost:3002';
let server;

beforeAll(async () => {
    try {
        environment.db.url = process.env.DB_URL || 'mongodb://localhost:27017/meat-api-test';
        environment.server.port = process.env.SERVER_PORT || 3002;
        server = new Server();
        await server.bootstrap();
        server.app.use('/users', usersRouter);
        User.remove({});
    } catch (err) {
        console.log(err);
    }
})

test('get /users', async () => {
    try {
        let response = await request(url).get('/users');
        expect(response.status).toBe(200);
        expect(response.body.items).toBeInstanceOf(Array);
    } catch (err) {
        fail(err);
    }
});

test('post /users', async () => {
    try {
        let response = await request(url).post('/users').send({
            name: 'User1',
            email: 'users1@gmail.com',
            password: '123',
            gender: 'Male'
        });
        expect(response.status).toBe(200);
        expect(response.body._id).toBeDefined();
        expect(response.body.password).toBeUndefined();
    } catch (err) {
        fail(err);
    }
})

最后这是错误

> jest

 FAIL  users/users.test.ts
  ● Test suite failed to run

    TypeError: server_1.Server is not a constructor

      3 | console.log(Server);
      4 | 
    > 5 | const server: Server = new Server();
        |                        ^
      6 | server.bootstrap()
      7 |     .then(server => {
      8 |         console.log(`Server is listening on port: ${server.app.get('port')}`);

      at Object.<anonymous> (index.ts:5:24)
      at Object.<anonymous> (server/routes.ts:1:1)
      at Object.<anonymous> (server/server.ts:6:1)
      at Object.<anonymous> (users/users.test.ts:3:1)

  console.log index.ts:3
    undefined

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        2.184s
Ran all test suites.
npm ERR! Test failed.  See above for more details.
4

0 回答 0