测试成功完成后,Jest不会终止

时间:2017-05-17 23:17:03

标签: jestjs supertest

我正在使用jest& supertest测试我的api端点,测试通过没有问题;但是jest永远不会退出我通常会看到的 Done in X time of time 语句。我希望确保--watch标志没有被使用,但事实并非如此。似乎与服务器的连接永远不会结束,因此jest会想知道下一步是什么。 UserFactory.generate()使用faker库创建虚假用户数据。

我在尝试解决此问题时感到茫然。我已经按照jest的帮助页面上推荐的策略进行操作,但没有运气,也在问题跟踪器中进行挖掘,但对类似问题一无所知。

这是我在运行测试套件时会看到的:

enter image description here

正如你所看到的那样,测试是7次通过。我告诉所有测试都已运行,然后morgan显示已发生的POSTjest从不退出所以实际上这是失败的,因为它会在任何CI服务器上超时,除非手动退出。

我尝试使用.end() & done().then() & done()代替async/await。他们都返回相同的最终结果,如果这是一个未解决jest的承诺的问题将会因未解决的承诺而错误,所以我无法理解为什么这不会终止,因为jest通常会

有没有人遇到过这样的问题?

user.controller.test.js

import mongoose from 'mongoose';
import request from 'supertest';
import { UserFactory } from '../../__mocks__';
import { User } from '../../modules';
import { config } from '../../utils';
import app from '../../';

const mockRoute = data => request(app).post(`${config.ENDPOINT}/user/sign-up`).send(data);

describe(`POST: /user/sign-up`, () => {
  // remove any user data from db prior to running tests.
  beforeAll(async () => { await User.remove(); });
  test('Returns status 201 on success.', async () => {
    // Returns the response object: res.status === { status }
    const { status }  = await mockRoute(UserFactory.generate());
    expect(status).toEqual(201);
  });
  afterAll(async () => {
    // drop connection to the collection
    const { users } = mongoose.connection.collections;
    await users.drop();
  });
});

用户/ routes.js

import { Router } from 'express';
import validate from 'express-validation';

import { signUp } from './controller';
import valid from './validation'

const routes = new Router();

/**
 * 1. Define the route: 'user/signup'.
 * 2. Validate the data being provided on the POST
 *    against valid.signUp object.
 * 3. Provide data to signUp controller method for
 *    creating a user in the database.
 */
 routes.post('/user/sign-up', validate(valid.signUp), signUp);

 export default routes;

用户/ controller.js

import HTTPStatus from 'http-status';
import User from './model';
import { config, filterBody } from '../../utils';

export const signUp = async (req, res, next) => {
  const filteredBody = filterBody(req.body, config.WHITELIST.users.signUp);
  try {
    const user = await User.create(filteredBody);
    return res.status(HTTPStatus.CREATED).json(user.toAuthJSON());
  } catch (e) {
    e.status = HTTPStatus.BAD_REQUEST;
    return next(e);
  }
}

用户/ model.js

import mongoose, { Schema } from 'mongoose';
import uniqueValidator from 'mongoose-unique-validator';
import { hashSync, compareSync } from 'bcrypt-nodejs';
import jwt from 'jsonwebtoken';

import { config } from '../../utils';

const UserSchema = new Schema({
  email: {
    type: String,
    unique: true,
    required: [true, 'Email is required!'],
    trim: true,
    validate: {
      validator(email) {
        const emailRegex = /^[-a-z0-9%S_+]+(\.[-a-z0-9%S_+]+)*@(?:[a-z0-9-]{1,63}\.){1,125}[a-z]{2,63}$/i;
        return emailRegex.test(email);
      },
      message: '{VALUE} is not a valid email!',
    }
   },
   password: {
      type: String,
      required: [true, 'Password is required!'],
      trim: true,
      minlength: [6, 'Password need to be longer!'],
      validate: {
        validator(password) {
        return password.length >= 6 && password.match(/\d+/g);
        },
      },
  }
}, { timestamps: true })

UserSchema.plugin(uniqueValidator, {
  message: '{VALUE} already taken!',
});

UserSchema.pre('save', function(next) {
  if (this.isModified('password')) {
   this.password = this._hashPassword(this.password);
   return next();
  }
  return next();
});


UserSchema.methods = {
  authenticateUser(password) {
    return compareSync(password, this.password);
  },
  _hashPassword(password) {
    return hashSync(password);
  },
  createToken() {
    return jwt.sign({ _id: this._id }, config.JWT_SECRET);
  },
  toAuthJSON() {
    return {
      _id: this._id,
      token: `JWT ${this.createToken()}`,
    };
  },
  toJSON() {
    return {
      _id: this._id,
      username: this.username,
    };
  },
};

let User;

try {
   User = mongoose.model('User');
} catch (e) {
   User = mongoose.model('User', UserSchema);
}

export default User;

用户/ validation.js

import Joi from 'joi';

export default {
   signUp: {
    body: {
      email: Joi.string().email().required(),
      password: Joi.string()
        .min(6)
        .regex(/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/)
        .required(),
    },
  },
};

middlewares.js

import bodyParser from 'body-parser';
import compression from 'compression';
import cors from 'cors';
import morgan from 'morgan';
import { userRoutes } from '../modules';

export default app => {
  app.use(compression());
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(cors());
  app.use(morgan('dev'));
  // applying api routes last.
  app.use('/api/v1', [userRoutes]);
}

index.js

import express from 'express';
import {
  database,
  config,
  middlewares,
} from './utils';

// Create instance of Express.
const app = express();
const MODE = process.env.NODE_ENV;

// Apply middlewares to Express.
middlewares(app);
// Connect to the environment determined database.
database(config.MONGO_URI)

app.listen(config.PORT, err => {
  if (err) { return console.error(err); }
  console.log(`App running on port: ${config.PORT} in ${MODE} mode.`);
});

export default app;

2 个答案:

答案 0 :(得分:9)

想出问题是我在afterAll()挂钩中做得不够。

我做了一个小型回购重现问题并从那里解决了问题,这是需要做的事情,以便成功完成测试套件后jest可以退出:

afterAll(async () => {
try {
  const { todos } = mongoose.connection.collections;
  // Collection is being dropped.
  await todos.drop()
  // Connection to Mongo killed.
  await mongoose.disconnect();
  // Server connection closed.
  await server.close();
} catch (error) {
  console.log(`
    You did something wrong dummy!
    ${error}
  `);
  throw error;
}

答案 1 :(得分:0)

这对我有用:

afterAll(async () => {
    try {
      // Connection to Mongo killed.
      await mongoose.disconnect();
    } catch (error) {
      console.log(`
        You did something wrong dummy!
        ${error}
      `);
      throw error;
    }
});