'How can I write a chai test for file uploading with multer?

I have the following code:

        it('Should create a new modulo with an image', function(done) {
            const moduloFake = aModulo(5);
            const createModuloFake = sinon.fake.resolves(moduloFake);
            const findOneFake = sinon.fake.resolves(null);
            sinon.replace(Modulo, 'create', createModuloFake);
            sinon.replace(Modulo, 'findOne', findOneFake);
            chai.request(app)
                .post('/api/v1/modulos')
                .set('Authorization', `Bearer ${token}`)
                .field('temaIndicador', moduloFake.temaIndicador)
                .field('id', moduloFake.id)
                .field('codigo', moduloFake.codigo)
                .field('activo', moduloFake.activo)
                .field('observaciones', moduloFake.observaciones)
                .field('color', moduloFake.color)
                .attach('urlImagen', 'uploads/images/avatar.jpg')
                .end(function (err, res) {
                    expect(createModuloFake.calledOnce).to.be.true;
                    expect(res).to.have.status(201);
                    expect(res.body.data).to.have.property('temaIndicador');
                    expect(res.body.data).to.have.property('codigo');
                    expect(res.body.data).to.have.property('activo');
                    expect(res.body.data).to.have.property('observaciones');
                    expect(res.body.data).to.have.property('color');
                    expect(res.body.data).to.have.property('urlImagen');
                    done();
                });
        })

It works as is intended, the only problem here is that every time someone runs that test, multer will upload the image (as it thinks it is a normal post and not a test post request)

Multer generating file

Is there a way to avoid this behavior and not 'upload' the file to the folder?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source