Hi, I'm creating an API with Node, Express and Mongoose. I also use Typescript and Gulp to transpil files into javascript.I tested my routes with Postman, all works fine. Now I want to write test with Mocha, Chai and Chai-Http. My first test is very simple but I got an error:users.router.spec.ts import "mocha" import * as chai from "chai" import chaiHttp = require("chai-http") // Require is required or bug import { should } from "chai" import app from "./../index" chai.use(chaiHttp) describe("Users", function() { describe("/POST user", function() { it("it should add a new user", done => { chai .request(app) .post("/api/users/add") .end((err, res) => { if (err) done(err) res.should.have.status(201) done() }) }) }) }) The error is: uncaughtException: Cannot read property 'server' of undefinedI'm not sure but I think the problem is the app parameter in the chai.request(), because if I try to change it for "chai.request(http://localhost:3000)", the error is replaced by a timeout problem.There some files of my app:index.ts import { App } from "./app" let app = new App().getApp() export default app app.ts export class App { private static readonly PORT: number = 3000 private app: express.Application private server: Server private port: string | number constructor() { this.createApp() this.config() this.createServer() this.middleware() this.database() this.routes() this.listenServer() } private createApp(): void { this.app = express() } private config(): void { this.port = process.env.PORT || App.PORT } private createServer(): void { this.server = createServer(this.app) } private listenServer(): void { this.server .listen(this.port, () => { logger.info("The server has started running on port %s", this.port) }) .on("close", () => { logger.info("The server has been closed") }) } private middleware(): void { // some middlewares... } private database(): void { // Connect to database } private routes(): void { let router = express.Router() this.app.use("/", router) this.app.use("/api/users", new UsersRouter().getRouter()) } public getApp(): express.Application { return this.app } } users.router.ts export class UsersRouter { private router: Router constructor() { this.router = Router() this.init() } private add(req: Request, res: Response, next: NextFunction): void { User.create({ email: "email", password: "password" }).then( user => { res.status(201).json({ data: user }) } ) } private init(): void { this.router.post("/add", this.add) } getRouter(): Router { return this.router } } A very simple test without using chai-http works fine (e.g: "hi".should.equal("hi")), so I guess my test environment is well implemented in my project. I'm trying to write test for the first time of my life, and I didn't find anything on the internet about this error. Thanks for your interest and reading this to the end.
Submitted May 10, 2018 at 12:29PM by GreenMonkeyBoy
No comments:
Post a Comment