Jul*_*son 5 mocha.js mongodb node.js chai
如何在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)到目前为止,这是我的帖子/创建路线:
该请求的伪代码是:
//检查响应是否成功
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)关于我做错的任何指示都表示赞赏.我输出的错误是:
1)帖子应该在POST/posts返回一个新帖子:错误:超过10000ms超时.对于异步测试和挂钩,确保调用"done()"; 如果退回承诺,确保它得到解决.
错误的ERR!代码ELIFECYCLE npm ERR!错误1 npm ERR!reddit_clone@1.0.0测试:mocha
测试超时,因为请求从未发送。
\n\n根据文档I\xe2\x80\x99m 没有看到任何表明您可以通过简单地将数据传递到post。库需要做出很多假设,例如序列化类型、标头等。
使用 JSON 负载执行 POST 请求的正确方法是:
\n\nchai\n .request(\'http://localhost:3000\')\n .post(\'/posts\')\n .send(head)\n .end((err, res) => {\n ...\n });\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
488 次 |
| 最近记录: |