不使用multer库进行测试

时间:2019-04-18 09:28:28

标签: node.js testing multer

我正在测试添加产品,我想添加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库?如何将照片传输到资料库,以便进行测试?为什么我的测试失败了,图像有问题

1 个答案:

答案 0 :(得分:1)

问题是您使用的Modules/mathmodule.i返回了图像链接,这是不希望的。

您需要将faker.image.image()函数添加到attach()函数中,以使文件可用于multer。如果有多个文件,则需要添加多个chai.request()调用。 另外,请从attach()中删除文件的参数,以避免出现任何不希望的错误。

getFakeProduct()

编辑:

由于chai在后台使用超级代理。他们的文档中提到您不能同时使用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]', 'tobi@learnboost.com') .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(); } }); attach()。相反,您需要使用send()

superagent documentation

中的示例
field()