有没有一种方法可以使用Jasmine NodeJS发送JPG文件?

4

我正在尝试使用FrisbyJS(基于Node的Jasmine)测试我的API。我想知道是否有人知道如何使用Jasmine提交/发送图像?

http://frisbyjs.com/

我的当前代码是...

var frisby = require('frisby');

var URL = 'http://localhost/api';

frisby.globalSetup({
  request: {
  headers: {
   'Content-Type': 'application/x-www-form-urlencoded',
   'Accept': 'application/json',
   'api': 'key'
  }
 },
 timeout: (30 * 1000)
});

frisby.create('submit an image')
  .post(URL + 'image', {images: '@test.jpg'}, {method: 'POST'})
  .expectStatus(200)
  .afterJSON(function(cart){
    console.log('made it!');
  })
}).toss();

我收到以下错误:

  1) Frisby Test: submit an image
[ POST http://localhost/api ]
  Message:
   timeout: timed out after 30000 msec waiting for HTTP Request timed out before completing
   Stacktrace:
    undefined

    Finished in 31.458 seconds

是的,图片test.jpg确实存在于与规范文件相同的文件夹中 :),这也是我执行规范本身(jasmine-node .)的地方。


你好,你能找到解决方案了吗? - Siddharth Sharma
我曾经遇到过同样的问题,最终使用了restler,这是一个比frisbyjs更好的替代品,在restler的文档中,你可以看到如何发送带有图像的数据。 - Siddharth Sharma
1个回答

4
我在https://github.com/vlucas/frisby/blob/master/examples/httpbin_multipart_spec.js的示例基础上找到了一个解决方案。
var frisby = require('frisby');
var fs = require('fs');
var path = require('path');
var FormData = require('form-data');

var contentPath = path.resolve(__dirname, './path/to/image.jpg');    
var form = new FormData();

form.append('file', fs.createReadStream(contentPath), {
  knownLength: fs.statSync(contentPath).size
});

frisby.create('Create content asset')
  .post(apiPath + '/assets', form, {
     json: false,
     headers: {
       'content-type': 'multipart/form-data; boundary=' + form.getBoundary(),
       'content-length': form.getLengthSync(),
     }
})
.expectStatus(201)
.toss()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接