Fre*_*ind 20 javascript unit-testing asynchronous jasmine
我正在尝试用Jasmine编写一些测试,但是现在有一个问题,如果有一些代码是异步的beforeEach
.
示例代码如下所示:
describe("Jasmine", function() {
var data ;
beforeEach(function(){
console.log('Before each');
getSomeDataFromRemote(function(res){
data = res;
});
});
it("test1", function() {
expect(data).toBe(something);
console.log('Test finished');
});
});
Run Code Online (Sandbox Code Playgroud)
你可以看到,beforeEach
我希望从远程获取一些数据,并将其分配给data
异步.
但是test1
当我试图验证时:
expect(data).toBe(something);
Run Code Online (Sandbox Code Playgroud)
数据是undefined
,因为getSomeDataFromRemote
尚未完成.
怎么解决?
Aar*_*ell 25
就像it
你内部的异步内容一样,你可以在beforeEach中使用runs
和waitsFor
:
define( 'Jasmine' , function () {
var data ;
beforeEach(function(){
runs( function () {
getSomeDataFromRemote(function(res){
data = res;
});
});
waitsFor(function () { return !!data; } , 'Timed out', 1000);
});
it("test1", function() {
runs( function () {
expect(data).toBe(something);
});
});
});
Run Code Online (Sandbox Code Playgroud)
虽然我会假设这是因为这是测试代码,我认为你应该getSomeDataFromRemote
在你的内部调用,it
因为那实际上是你正在测试的;)
您可以在我为异步API编写的一些测试中看到一些更大的示例:https://github.com/aaronpowell/db.js/blob/f8a1c331a20e14e286e3f21ff8cea8c2e3e57be6/tests/public/specs/open-db.js
Tim*_*gus 16
要小心,因为在新的Jasmine 2.0中,这将改变,它将是摩卡风格.你必须done()
在beforeEach()
和中使用函数it()
.例如,假设您想使用jQuery在LAMP服务器中测试页面是否存在且不为空$.get
.首先,您需要将jQuery添加到SpecRunner.html
文件中,并在您的spec.js
文件中:
describe('The "index.php" should', function() {
var pageStatus;
var contents;
beforeEach(function (done) {
$.get('views/index.php', function (data, status) {
contents = data;
pageStatus = status;
done();
}).fail(function (object, status) {
pageStatus = status;
done();
});
});
it('exist', function(done) {
expect(status).toBe('success');
done();
});
it('have content', function(done) {
expect(contents).not.toBe('');
expect(contents).not.toBe(undefined);
done();
});
});
Run Code Online (Sandbox Code Playgroud)
如您所见,您将该函数done()
作为参数传递给beforeEach()
和it()
.当您运行测试时,在调用函数it()
之前不会启动,因此在您收到服务器的响应之前,您不会启动预期.done()
beforeEach()
该页面存在
如果页面存在,我们从服务器的响应中捕获状态和数据,然后我们调用done()
.然后我们检查状态是否"成功"以及数据是否为空或未定义.
该页面不存在
如果页面不存在,我们从服务器的响应中捕获状态,然后我们调用done()
.然后我们检查状态是否"成功"以及数据是否为空或未定义(必须是因为文件不存在).
归档时间: |
|
查看次数: |
13567 次 |
最近记录: |