2015-01-20 18 views
5

: Aşağıda Düğüm Ekspres test sahte res.status (durum) .json (obj) Benim yöntemi test etmek çalışırken aşağıdaki hatayı alıyorum

TypeError: Cannot call method 'json' of undefined

benim kodudur i için aynı hatayı alırdım Res.status'u test yönteminden kaldırırsam, 'status'. Bu fonksiyonu test ederken

res.status(404).json(error);

i 'json' ne dereceye kadar belirler

yüzden bir istisna atılan olsun yok.

stores.js

{ //the get function declared above (removed to ease of reading) 
     // using a queryBuilder 
     var query = Stores.find(); 
     query.sort('storeName'); 
     query.exec(function (err, results) { 
      if (err) 
       res.send(err); 
      if (_.isEmpty(results)) { 
       var error = { 
        message: "No Results", 
        errorKey: "XXX" 
       } 
       res.status(404).json(error); 
       return; 
      } 
      return res.json(results); 
     }); 
    } 

storesTest.js chainable yöntemleri için

it('should on get call of stores, return a error', function() { 

    var mockFind = { 
     sort: function(sortOrder) { 
      return this; 
     }, 
     exec: function (callback) { 
      callback('Error'); 
     } 
    }; 

    Stores.get.should.be.a["function"]; 

    // Set up variables 
    var req,res; 
    req = {query: function(){}}; 
    res = { 
     send: function(){}, 
     json: function(err){ 
      console.log("\n : " + err); 
     }, 
     status: function(responseStatus) { 
      assert.equal(responseStatus, 404); 
     } 
    }; 

    StoresModel.find = sinon.stub().returns(mockFind); 

    Stores.get(req,res); 

cevap

10

Kongre her ucunda this döndürmektir. Testlerde, res nesnesini atarsınız. Bu nesne üzerindeki her yöntem return this; ile bitmelidir. Eğer o şekilde tanımlamak eğer yanlış pozitif testler yol açabilir, böylece chainable değildir json` `

res = { 
    send: function(){ }, 
    json: function(err){ 
     console.log("\n : " + err); 
    }, 
    status: function(responseStatus) { 
     assert.equal(responseStatus, 404); 
     // This next line makes it chainable 
     return this; 
    } 
} 
+1

' send' ve. https://github.com/strongloop/express/blob/master/lib/response.js#L222 – Chris

+0

Sanırım haklısınız - 'statü' yöntemi gerçekten zincirlenebilir olmak için gereken tek şey. Cevabımı güncelledim. –

+0

Bu dönüş hakkında sinon dökümanından bahsetmiştim. durumu gibi bir şey yapabilmeliyiz: sinon.stub(). ReturnThis() –

İlgili konular