2015-09-07 26 views
5

ile çalışmaya çalışmıyor Verileri almak için bir 3. lib kullanmakta olan bir JS'yi test etmek istiyorum, bu yüzden bu uygulamada mock kullanıyorum. Doğrudan testte dediğimde çalışıyor. Ancak, kaynak kodunda kullanıldığında çalışmaz.jest mock application required ('')

İşte gerektirir ait Siparişiniz yanlış kod

//Source implementation 

var reference = require('./reference'); 

module.exports = { 
    getResult: function() { 
    return reference.result(); 
    } 
}; 


//Test code 

jest.dontMock('./foo'); 
jest.dontMock('console'); 

describe('descirbe', function() { 
    var foo = require('./foo'); 

    it('should ', function() { 
    var reference = require('./reference'); 

    reference.result.mockImplementation(function (a, b, c) { 
     return '123' 
    }); 

    console.log(foo.getResult()); // undefined 
    console.log(reference.result()); // 123 
    }); 

}); 

cevap

2

olduğunu. Senin alay reference önce ./foo ihtiyaç duyduğunuzda daha sonra foo s Jest automocking göre tanımsız olacaktır.

jest.dontMock('./foo');                                                     

describe('descirbe', function() {                                                   
    it('should ', function() {                                                    
     var reference = require('./reference');                                                
     reference.result.mockImplementation(function (a, b, c) { 
      return '123'; 
     });                                                
     var foo = require('./foo');                                                   

     console.log('ferr', foo.getResult()); // ferr 123                                                 
    });                                                          
}); 
2

hattı

var foo = require('./foo');

describe değerlendirildi ve foo depolanır.

Daha sonra, it bloğunda, bunu çözüyorsunuz, ancak bu, foo numaralı eski referansa uygulanmıyor.

foo arayarak, mockImplementation numaralı çağrı hata düzeltmesiyle giderilecektir.

//Test code 

jest.dontMock('./foo'); 
jest.dontMock('console'); 


describe('describe', function() { 

    it('should ', function() { 
    var reference = require('./reference'); 

    reference.result.mockImplementation(function (a, b, c) { 
     return '123' 
    }); 
    var foo = require('./foo'); 

    console.log(foo.getResult()); // undefined 
    console.log(reference.result()); // 123 
    }); 

});