node.js - 不执行使用 multer 库的测试

标签 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库?如何将照片传输到图库以便测试运行?为什么测试失败我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]', '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();
    }
  });

编辑:

因为 chai 在后台使用 superagent。他们的文档中提到您不能同时使用 attach()send() 。您需要使用 field()

示例来自 superagent documentation

 request
   .post('/upload')
   .field('user[name]', 'Tobi')
   .field('user[email]', 'tobi@learnboost.com')
   .field('friends[]', ['loki', 'jane'])
   .attach('image', 'path/to/tobi.png')
   .then(callback);

关于node.js - 不执行使用 multer 库的测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55743051/

相关文章:

node.js - 将 mers 与backbone.js 结合使用

java - 使用另一个 Suite 类启动 Suite 类

node.js - (Express js 4 Multer) 在文件上传之前检查表单字段(如果为空)

node.js - 用于 SaaS 的 MongoDB 中的多个数据库

mysql - 如何在不知道元素id的情况下删除元素,只需在数据库中排序

javascript - 我的 socket.io 客户端出现 io not defined 错误

javascript - 在基于 Maven 的项目中自动化 JavaScript 测试

javascript - 尝试测试组件时找不到模块 'react'

node.js - 在生产模式下无法访问我存储个人资料图片的路径

javascript - 如何使用 multer 或 body-parser 上传文件