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

Jul*_*son 5 mocha.js mongodb node.js chai

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

    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.
            })
        })
    })
    
    Run Code Online (Sandbox Code Playgroud)

  1. 到目前为止,这是我的帖子/创建路线:

  2. 该请求的伪代码是:

  3. //现在有多少帖子?
  4. //请求创建另一个
  5. //检查数据库中是否还有一个帖子
  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)
            })
        });
    })
    
    Run Code Online (Sandbox Code Playgroud)
  8. 关于我做错的任何指示都表示赞赏.我输出的错误是:

1)帖子应该在POST/posts返回一个新帖子:错误:超过10000ms超时.对于异步测试和挂钩,确保调用"done()"; 如果退回承诺,确保它得到解决.

错误的ERR!代码ELIFECYCLE npm ERR!错误1 npm ERR!reddit_clone@1.0.0测试:mocha

Jam*_*mes 0

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

\n\n

根据文档I\xe2\x80\x99m 没有看到任何表明您可以通过简单地将数据传递到post。库需要做出很多假设,例如序列化类型、标头等。

\n\n

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

\n\n
chai\n  .request(\'http://localhost:3000\')\n  .post(\'/posts\')\n  .send(head)\n  .end((err, res) => {\n    ...\n  });\n
Run Code Online (Sandbox Code Playgroud)\n