如何在 mocha 和 mongoDB 中使用 chai 向节点发出 post 请求

How to make a post request with node using chai in mocha and mongoDB

  1. 如何在 mocha 和 mongoDB 中使用 chai 向节点发出 POST 请求。 我有一个包含我的 get 请求和 post 请求的测试文件。我下面的代码等于我的 get 请求,它通过了我为其设置的 1 次测试,但是我在创建 post 请求时遇到了问题,我不明白我应该做什么。获取请求:

    const chai = require('chai');
    const expect = chai.expect;
    const chaiHttp = require('chai-http')
    
    chai.use(chaiHttp)
    
    describe('site', () => {       // Describe what you are testing
        it('Should have home page', (done) => { // Describe 
            // In this case we test that the home page loads
            chai.request('localhost:3000')
            chai.get('/')
            chai.end((err, res) => {
                if (err) {
                    done(err)
                }
                res.status.should.be.equal(200)
                done()   // Call done if the test completed successfully.
            })
        })
    })
    

  1. 这是我目前的 post/create 路线:

  2. 本次请求的伪代码为:

  3. // 现在有多少个 post?
  4. // 请求创建另一个
  5. // 检查数据库中是否多了一个post
  6. //检查响应是否成功

  7. POST 请求:

    const chai = require('chai')
    const chaiHttp = require('chai-http')
    const should = chai.should()
    chai.use(chaiHttp)
    const Post = require('../models/post');
    
    describe('Posts', function() {
        this.timeout(10000);
        let countr;
    
        it('should create with valid attributes at POST /posts', function(done) {
            // test code
            Post.find({}).then(function(error, posts) {
                countr = posts.count;
    
                let head = {
                    title: "post title", 
                    url: "https://www.google.com", 
                    summary: "post summary"
                }
                chai.request('localhost:3000')
                chai.post('/posts').send(head)
                chai.end(function(error, res) {
                    //console.log('success')
                })
            }).catch(function(error) {
                done(error)
            })
        });
    })
    
  8. 如有任何关于我做错的指示,我们将不胜感激。我对这个错误的输出是:

1) 帖子 应该 return 一个新的 post 在 POST /posts: 错误:超时超过 10000 毫秒。对于异步测试和挂钩,确保 "done()" 被调用;如果return使用 Promise,请确保它已解析。

npm 错误!代码生命周期 错误!错误号 1 错误! reddit_clone@1.0.0 测试:mocha

测试超时,因为从未发送请求。

基于 docs,我没有看到任何迹象表明您可以通过简单地将数据传递到 post 函数来执行 post。这里的图书馆需要做出很多假设,例如序列化类型,headers 等

使用 JSON 负载执行 POST 请求的正确方法是:

chai
  .request('http://localhost:3000')
  .post('/posts')
  .send(head)
  .end((err, res) => {
    ...
  });