chai.request附加文件数组

时间:2017-05-01 18:43:20

标签: node.js unit-testing chai

我正在用chai.request编写一个通用的测试函数,这就是我所拥有的:

//this is in some function
    var file = fs.readFileSync(__dirname + '/../test/files/' + args.fileName);
    chai.request(server)
            .post('/v2')
            .field('email', args.email)
            .field('subject', args.subject)
            .attach('fileName', file, args.fileName)
            .end((err, res) => {
                //some test conditions

                done();
            });

如果只传递了1个文件,那么这很有用,问题是有时我需要传入一个文件数组,但是当我不确定文件数量到来时我不知道如何附加这些文件英寸

PS:有些测试需要同时传入多个文件,所以简单地循环整个事情两次都行不通,我不得不以某种方式遍历.attach部分

3 个答案:

答案 0 :(得分:0)

在为我正在处理的应用程序编写测试时遇到了同样的问题,这是我在该问题上发现的唯一问题,也没有在文档中找到任何问题。

对我有用的解决方案是将.n附加到字段名称,如下所示:

chai.request(server)
    .post('/v2')
    .field('email', args.email)
    .field('subject', args.subject)
    .attach('fileName.0', file, args.fileName)
    .attach('fileName.1', file1, args.fileName1)
    .attach('fileName.2', file2, args.fileName2)
    .end((err, res) => {
        //some test conditions
        done();
    });

答案 1 :(得分:0)

您可以将文件,文件数组和常规字段组合在一起

  CREATE TABLE gender (
        [name] VARCHAR (20)
        CONSTRAINT gender_pk PRIMARY KEY ([name])
    );
    
    CREATE TABLE user_info (
        id int PRIMARY KEY IDENTITY (1,1),
        usr_name VARCHAR (30) NOT NULL,
        f_name VARCHAR (30) NOT NULL,
        l_name VARCHAR (30),
        b_day DATE,
        email VARCHAR  (120) NOT NULL,
        gender VARCHAR (20) NOT NULL,
        genderIntrest VARCHAR (20) NOT NULL,
        CONSTRAINT gender_fk FOREIGN KEY (gender) REFERENCES gender ([name]),
        CONSTRAINT genderIntrest_fk FOREIGN KEY (genderIntrest) REFERENCES gender ([name]),
    );
    
    INSERT INTO gender ([name])
    VALUES 
    ('Female'),
    ('Male')
    
    INSERT
      INTO user_info 
         ( usr_name, f_name, l_name, b_day, gender, genderIntrest, email)
    VALUES 
         ('JMAN', 'JOHN', 'DOE', '1990-01-01','Male','Female', 'EX@EMAIL'),
         ('JAM','JANE', 'DOE', '1995-05-02','Female','Female', 'EX@EMAIL'),
         ('NMAN','NICK', 'WEBB', '1999-06-22','Male','Female','EX@EMAIL'),
         ('LOBA','LOLA', 'LILLY', '1994-01-08','Female','Female','EX@EMAIL'),
         ('NOTSPMAN','PETER', 'PARKER','1985-11-25','Male','Female','EX@EMAIL');
    
    SELECT * FROM user_info;

答案 2 :(得分:0)

我发现解决此问题的最简洁方法如下:

const fileCount = 10
let req = chai.request(app).post(`${baseUrl}/upload`)

Array.from(new Array(fileCount)).forEach((_, index) => {
  req = req.attach('files', Buffer.from('?'), `file-${index}.png`)
})

const response = await req