简体   繁体   English

使用 Mocha 在 NodeJs 中测试删除方法时出错

[英]Error while testing delete method in NodeJs with Mocha

I'm developing a billboard app to learn new technologies and i'm currently having problems trying to test the DELETE method of the API using Mocha.我正在开发一个广告牌应用程序来学习新技术,我目前在尝试使用 Mocha 测试 API 的 DELETE 方法时遇到问题。

I've been trying different approaches for it, but i couldn't find a solution yet.我一直在尝试不同的方法,但我还没有找到解决方案。 I'm using NodeJs and Hapi for the back-end server我使用 NodeJs 和 Hapi 作为后端服务器

const mongoose = require('mongoose')
const chai = require('chai')
const hapiServer = require('../../../index')
const expect = require('chai').expect
const should = chai.should()
chai.use(require('chai-http'))

before(async () => {
  const server = await hapiServer()
  global.url = 'http://localhost:3000'
})
after(async () => {
  await mongoose.connection.close()
  //await mongoose.connection.db.dropCollection()
})

const id = new mongoose.Types.ObjectId('5cd8a0eefc06344accd62a76')

describe('Movies API', () => {

  it('Should DELETE a single movie', async () => {
      const response = await chai.request(global.url)
        .delete('/api/movies/' + '5cd8a0eefc06344accd62a77')
      response.should.have.status(202)
  })
})

Here's the index.js这是 index.js

const Hapi = require('@hapi/hapi')
const Inert = require('@hapi/inert')
const Vision = require('@hapi/vision')
const HapiSwagger = require('hapi-swagger')
const mongoose = require('mongoose')
const mongo = require('./config/mongo')
const Pack = require('./package')

const start = async () => {

  const server = await new Hapi.Server({
    host: 'localhost',
    port: 3000,
  })

  // MongoDB Connection
  try{
    await mongoose
      .connect(mongo.configuration.getUri(process.env.NODE_ENV), {useNewUrlParser: true})
    console.log('MongoDB Connected...')
  } catch(err) {
    console.log(err)
  }

  const swaggerOptions = {
    info: {
      title: 'Billboard API Documentation',
      version: Pack.version,
    },
  }

  await server.register([
    Inert,
    Vision,
    {
      plugin: HapiSwagger,
      options: swaggerOptions
    }
  ]);

  try {
    await server.start()
    console.log('Server running at:', server.info.uri)
  } catch(err) {
    console.log(err)
  }

  // Register Plugins
  const moviesRoutes = require('./plugins/movies/routes')

  server.route(moviesRoutes)
}

start()

module.exports = start

So, the the rest of the api tests are similar and they work excelent.因此,其余的 api 测试是相似的,并且它们运行良好。 But when i try to test this method i get this response:但是当我尝试测试这个方法时,我得到了这个响应:

error: Error: cannot DELETE /api/movies/5cd8a0eefc06344accd62a77 (404)
      at Response.toError (C:\Users\lucas\billboard-backend\node_modules\superagent\lib\node\response.js:94:15)
      at ResponseBase._setStatusProperties (C:\Users\lucas\billboard-backend\node_modules\superagent\lib\response-base.js:123:16)
      at new Response (C:\Users\lucas\billboard-backend\node_modules\superagent\lib\node\response.js:41:8)
      at Test.Request._emitResponse (C:\Users\lucas\billboard-backend\node_modules\superagent\lib\node\index.js:752:20)
      at C:\Users\lucas\billboard-backend\node_modules\superagent\lib\node\index.js:916:38
      at IncomingMessage.<anonymous> (C:\Users\lucas\billboard-backend\node_modules\superagent\lib\node\parsers\json.js:19:7)
      at IncomingMessage.emit (events.js:201:15)
      at endReadableNT (_stream_readable.js:1130:12)
      at processTicksAndRejections (internal/process/task_queues.js:84:9) {
    status: 404,
    text: '{"statusCode":404,"error":"Not Found","message":"Not Found"}',
    method: 'DELETE',
    path: '/api/movies/5cd8a0eefc06344accd62a77'

Any ideas of why is this happening?为什么会发生这种情况的任何想法?

You need to add a route like this in your routes file assuming you're using controllers假设您正在使用控制器,则需要在路由文件中添加这样的路由

const express = require('express')
const router = express.Router()
const movieController = require('../controllers/movie.controller')

router.delete('/api/movies/:movieId', movieController.deleteMovie)

module.exports = router

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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