gpt4 book ai didi

jasmine - 对 Strongloop Loopback.io 模型的远程方法进行单元测试

转载 作者:行者123 更新时间:2023-12-02 21:06:11 26 4
gpt4 key购买 nike

我正在尝试使用 jasmine 为环回模型编写单元测试。我的模型具有通常的 CRUD 端点,但我定义了一个自定义的“/products/:id/upload”端点,它需要一个包含文件的表单。

我的模型看起来像

'use strict';

var loopback = require('loopback');

var ProductSchema = {
location: {
type: String,
required: true
},
version: {
type: String,
required: true
},
id: { type: Number, id: 1, generated: true }
};

var opts = {
strict: true
};

var dataSource = loopback.createDataSource({
connector: loopback.Memory
});
var Product = dataSource.createModel('Product', ProductSchema, opts);


Product.beforeRemote('upload', function(ctx){
var uploader = function(req, res){
// parse a multipart form
res({
result:'success'
});
};
function createProduct(uploaderResult){
// create a product out of the uploaded file
ctx.res.send({
result: uploaderResult.result
});
}
uploader.upload(ctx.req, createProduct);
});

Product.upload = function () {
// empty function - all the logic takes place inside before remote
};

loopback.remoteMethod(
Product.upload,
{
accepts : [{arg: 'uploadedFiles', http: function(ctx){
return function() {
return { files : ctx.req.body.uploadedFiles, context : ctx };
};
}},
{arg: 'id', type: 'string'}],
returns : {arg: 'upload_result', type: String},
http: {path:'/:id/upload', verb: 'post'}
}
);

module.exports = Product;

我的最终目标是测试“createProduct”的逻辑。我的测试看起来像

'use strict';

describe('Product Model', function(){
var app = require('../../app');
var loopback = require('loopback');
var ProductModel;
beforeEach(function(){
app = loopback();
app.boot(__dirname+'/../../'); // contains a 'models' folder
ProductModel = loopback.getModel('Product');
var dataSource = loopback.createDataSource({
connector: loopback.Memory
});

ProductModel.attachTo(dataSource);
});

it('should load file ', function(){
console.log(ProductModel.beforeRemote.toString());
console.log(ProductModel);
ProductModel.upload();
});
});

通过调用ProductModel.upload();我希望触发 before 远程钩子(Hook)来执行 createProduct。我可以单独测试“createProduct”,但随后我会忽略 createProduct 最终因上传而被调用的事实。

明确地说,核心问题是:如何在单元测试中执行远程方法 Hook ?

最佳答案

建议使用supertest作为一个http服务器。下面是一个代码片段,说明如何在 jasmine 中执行此操作

describe('My product suite', function(){
var request = require('supertest');
var app;

beforeEach(function(){
app = loopback();
// don't forget to add REST to the app
app.use(app.rest());
});

it('should load file', function() {
request(app).post('/products/id-of-existing-product/upload')
.attach('file', 'path/to/local/file/to/upload.png')
.expect(200)
.end(function(err, res) {
if (err) return done(err);
// res is the HTTP response
// you can assert on res.body, etc.
});
});
});

关于jasmine - 对 Strongloop Loopback.io 模型的远程方法进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24410629/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com