如何使用 chai-http 跟踪链接
How to follow links using chai-http
我有一个 API 接受图像文件作为输入,上传它,并且 returns 永久 link 到上传的图像。
返回样本JSON:
{ "url": "localhost:3000/public/uploads/1471759901731.jpg" }
我的测试,使用 mocha 和 chai-http:
it('should upload single valid picture on /pictures POST', function(done) {
chai.request(app)
.post('/pictures')
.attach('picture', fs.readFileSync('test/test_data/banana.png'), 'banana.png')
.end(function(err, res) {
res.should.have.status(200);
res.should.be.json;
res.body.should.be.a('object');
res.body.should.have.property('url');
// should follow the url, ensure status 200
// follow res.body.url
done();
});
});
我如何遵循 url 以确保其有效且 returns 状态 200?
经过反复试验,我终于成功了。
it('should upload single valid picture on /pictures POST', function(done) {
chai.request(app)
.post('/pictures')
.attach('picture', fs.readFileSync('test/test_data/banana.png'), 'banana.png')
.end(function(err, res) {
res.should.have.status(200);
res.should.be.json;
res.body.should.be.a('object');
res.body.should.have.property('url');
// remove hostname from url
var pic_url = res.body.url;
pic_url = pic_url.split('/');
pic_url = '/' + pic_url.splice(1).join('/');
// follow the link
chai.request(app)
.get(pic_url)
.end(function(err, res) {
res.should.have.status(200);
content_type = res.header['content-type'].split('/')[0];
(content_type).should.equal('image');
done();
});
});
});
但这似乎不是最优雅的解决方案。我找不到其他人将 chai.request(app)
嵌套在 chai.request(app)
中。
我有一个 API 接受图像文件作为输入,上传它,并且 returns 永久 link 到上传的图像。
返回样本JSON:
{ "url": "localhost:3000/public/uploads/1471759901731.jpg" }
我的测试,使用 mocha 和 chai-http:
it('should upload single valid picture on /pictures POST', function(done) {
chai.request(app)
.post('/pictures')
.attach('picture', fs.readFileSync('test/test_data/banana.png'), 'banana.png')
.end(function(err, res) {
res.should.have.status(200);
res.should.be.json;
res.body.should.be.a('object');
res.body.should.have.property('url');
// should follow the url, ensure status 200
// follow res.body.url
done();
});
});
我如何遵循 url 以确保其有效且 returns 状态 200?
经过反复试验,我终于成功了。
it('should upload single valid picture on /pictures POST', function(done) {
chai.request(app)
.post('/pictures')
.attach('picture', fs.readFileSync('test/test_data/banana.png'), 'banana.png')
.end(function(err, res) {
res.should.have.status(200);
res.should.be.json;
res.body.should.be.a('object');
res.body.should.have.property('url');
// remove hostname from url
var pic_url = res.body.url;
pic_url = pic_url.split('/');
pic_url = '/' + pic_url.splice(1).join('/');
// follow the link
chai.request(app)
.get(pic_url)
.end(function(err, res) {
res.should.have.status(200);
content_type = res.header['content-type'].split('/')[0];
(content_type).should.equal('image');
done();
});
});
});
但这似乎不是最优雅的解决方案。我找不到其他人将 chai.request(app)
嵌套在 chai.request(app)
中。