jeudi 21 juillet 2016

using chai's should() assertion style to test a PUT method

I am trying to test an update method in a (very) simple shopping list app using chai's should() assertion style. There are currently three items on the list: name: Broad beans, id: 0 name: Tomatoes, id: 1 name: Peppers, id: 2

it('should edit an item on PUT', function(done){
        chai.request(app)
            .put('/items/0')
            .send({
                'name': 'Colin',
                'id': 0
            })
            .end(function(err, res) {
              should.equal(err, null);
              res.should.have.status(200);
              res.body.name.should.equal('Colin');
              storage.items[0].should.be.a('object');
              storage.items[0].should.have.property('id');
              storage.items[0].should.have.property('name');
              storage.items[0].id.should.be.a('number');
              storage.items[0].name.should.be.a('string');
              storage.items[0].name.should.equal('Colin');
              done();
            });
    });

The following is my update method and put

/**
 * update()
 * If id match found, replaces storage item with passed in item
 * @param: item (Object) { id: Number, name: String }
 * @return: item (Object) or undefined
 */
Storage.prototype.update = function(item) {
    for (index in this.items) {
        var element = this.items[index];
        console.log(item);
        console.log(element);
        if (parseInt(item.id) == element.id) {
            element.name = item.name;
            return element;
        }
    }
};

 app.put('/items/:id', jsonParser, function(req, res) {
    if (!req.params.id) {
        return res.sendStatus(404);
    }

    var item = storage.update({
        id: req.params.id,
        name: req.body.name 
    });
    storage.update(item);

    res.status(200).json(item);
});

I just want this damn test to pass, but when i run at like this, i just get an uncaught assertion error: expected 'peppers' to equal 'colin' and I cant pinpoint the source of the issue. Hope this isnt too much info.

Aucun commentaire:

Enregistrer un commentaire