2013-04-12 13 views
5

Próbuję wstrzyknąć jQuery w moim teście, ale pojawia się następujący błąd:

ReferenceError: nie można odnaleźć zmienna: $

To jest Ruby on Rails aplikacja próbuję przetestować, działając na WEBrick. Oto cały kod:

var casper = require('casper').create({ 
    clientScripts: ['jquery-1.9.1.min.js'] 
}); 

//make sure page loads 
casper.start('http://127.0.0.1:3000', function() { 
    this.test.assertTitle('EZpub', 'EZpub not loaded'); 
}); 

//make sure all 3 fridges are displayed 
casper.then(function() { 
    //get fridges 
    var fridges = $('a[href^="/fridges/"]'); 
    this.test.assert(fridges.length == 3, 'More or less than 3 fridge links shown'); 
}); 

casper.run(function() { 
    this.echo('Tests complete'); 
}); 

Odpowiedz

14

z dokumentacji wygląda jak trzeba użyć evaluate() aby uzyskać odwołanie do strony, która jest ładowany

Note The concept behind this method is probably the most difficult to understand when discovering CasperJS. As a reminder, think of the evaluate() method as a gate between the CasperJS environment and the one of the page you have opened; everytime you pass a closure to evaluate(), you're entering the page and execute code as if you were using the browser console.

casper.then(function() { 
    var fridges = casper.evaluate(function(){ 
     // In here, the context of execution (global) is the same 
     // as if you were at the console for the loaded page 
     return $('a[href^="/fridges/"]'); 
    }); 
    this.test.assert(fridges.length == 3, 'More or less than 3 fridge links shown'); 
}); 

jednak pamiętać, że możesz zwracać tylko proste obiekty, dlatego nie możesz uzyskać dostępu do obiektów jQuery poza oceną (to znaczy, nie możesz zwrócić obiektu JS), więc musisz zwrócić tylko to, co jest wymagane do przetestowania, takie jak następujące:

casper.then(function() { 
    var fridgeCount = casper.evaluate(function(){ 
     // In here, the context of execution (global) is the same 
     // as if you were at the console for the loaded page 
     return $('a[href^="/fridges/"]').length; 
    }); 
    this.test.assert(fridgeCount === 3, 'More or less than 3 fridge links shown'); 
});  
+1

Nie wierzę, że to jest problem. Jeśli niepoprawnie przeliteruję ścieżkę, otrzymuję błąd: Nie powiodło się wstrzyknięcie strony klienta jquey-1.9.1.min.js, której nie otrzymuję z bieżącym kodem. – Cailen

+0

@Cailen, ustaw nową odpowiedź –

+0

DZIĘKI! Umieszczenie go w funkcji evaluate() jest poprawnym podejściem. – Cailen