我正在测试添加产品,我想添加10个产品,但问题是我无法将图像传输到https://www.npmjs.com/package/multer库。
我的代码是:
import { expect } from 'chai';
import chai from 'chai';
import chaiHttp from 'chai-http';
import server from '../src/index';
import db from '../src/db/database';
chai.use(chaiHttp);
import constants from './tool/constants';
import utils from './tool/utils';
let addProductCount = 10;
describe('Test products', () => {
describe('POST /api/products/add', () => {
it(`should create ${addProductCount} products with 0...1000 price`, (done) => {
let operationCount = addProductCount;
for (let i = 0; i < addProductCount; i++) {
let product = utils.getFakeProduct(2, 1000);
chai.request(server)
.post('api/products/add')
.set('token', constants.merchantToken)
.send(product)
.end((err, res) => {
operationCount--;
expect(res).have.status(200);
expect(res.body).have.property('message');
expect(res.body.message).to.be.equal('Product added');
if (operationCount == 0) {
done();
}
});
}
});
});
});
...
function getFakeProduct(lowerPrice, upperPrice) {
let currentDate = faker.date.recent();
let original_price = getRandomInt(lowerPrice, upperPrice);
return {
product_name: faker.commerce.productName(),
product_description: `${faker.commerce.productAdjective()} ${faker.commerce.productAdjective()}`,
original_price,
sale_price: original_price - getRandomInt(lowerPrice, original_price - 1),
starting_date: currentDate,
end_date: moment(currentDate).add(1, 'days'),
product_photos: faker.image.image(),
quantity_available: faker.random.number(50),
categories: 'HOME APPLIANCES',
};
}
...
//handles url http://localhost:8081/api/products/add/
router.post('/add', upload, validatorAdd, async (req, res) => {
...
if (!req.files.product_photos) {
return res.status(422).json({
name: 'MulterError',
message: 'Missing required image file',
field: 'product_photos'
});
}
let photos = addProductPhotos(req.files.product_photos);
let user_id = 0;
let product = new Product(
user_id,
req.body.product_name,
req.body.product_description,
req.body.original_price,
req.body.sale_price,
discount,
moment().format(),
req.body.starting_date,
req.body.end_date,
photos,
req.body.quantity_available,
req.body.categories,
merchant_id,
);
await db.query(product.getAddProduct());
return res.status(200).json({
message: 'Product added'
});
});
...
'use strict';
import multer, { memoryStorage } from 'multer';
import path from 'path';
let storage = memoryStorage()
let upload = multer({
storage: storage,
limits: {
fileSize: 1000000
},
fileFilter: (req, file, cb) => {
console.log(file)
let ext = path.extname(file.originalname).toLowerCase();
if (ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg') {
return cb(null, false);
}
cb(null, true);
}
}).fields([{
name: 'user_avatar',
maxCount: 1
},
{
name: 'product_photos',
maxCount: 3
},
{
name: 'store_photos',
maxCount: 3
}
]);
export default upload;
...
我收到错误Uncaught TypeError: Cannot use 'in' operator to search for 'status' in undefined
。
如何测试multer库?如何将照片传输到库以便测试运行?为什么测试失败我的ponma,图像问题
问题是你使用faker.image.image()
返回图像链接,这是不希望的。
您需要将attach()
函数添加到chai.request()
函数中,以便为multer提供可用的文件。如果有多个文件,则需要添加多个attach()
调用。另外,从getFakeProduct()
中删除文件参数以避免任何意外错误。
const fs = require('fs');
chai
.request(server)
.post('api/products/add')
.set('token', constants.merchantToken)
.field('product_name', faker.commerce.productName())
// .filed() ... etc
.field('user[email]', '[email protected]')
.field('friends[]', ['loki', 'jane'])
.attach('product_photos', fs.readFileSync('/path/to/test.png'), 'test.png')
.end((err, res) => {
operationCount--;
expect(res).have.status(200);
expect(res.body).have.property('message');
expect(res.body.message).to.be.equal('Product added');
if (operationCount == 0) {
done();
}
});
编辑:
由于柴在引擎盖下使用superagent。在他们的文档中提到,你不能一起使用attach()
和send()
。你需要使用field()
。
request
.post('/upload')
.field('user[name]', 'Tobi')
.field('user[email]', '[email protected]')
.field('friends[]', ['loki', 'jane'])
.attach('image', 'path/to/tobi.png')
.then(callback);