【问题标题】:Don't know how to test this asyn function with Jasmine不知道如何用 Jasmine 测试这个异步函数
【发布时间】:2015-11-23 11:04:03
【问题描述】:
asynFn(url, callback)

这个函数接受一个 url 并触发一些 xhr 请求,然后使用callback(result) 发回处理后的结果。我应该如何测试它?

(我已经直接在 Chrome 中运行了asynFn,它运行良好。)

我尝试使用jasmine-ajax 来存根请求,但expect 不起作用。

describe('a test', function() {
  var callback

  beforeAll(function() {
    jasmine.Ajax.install()

    jasmine.Ajax.stubRequest('fake/path1').andReturn({
      status: 200,
      contentType: 'text/plain',
      responseText: 'yay'
    })

    jasmine.Ajax.stubRequest('fake/path2').andReturn({
      status: 200,
      contentType: 'text/plain',
      responseText: 'yay2'
    })

    // ...
  })

  afterAll(function() {
    jasmine.Ajax.uninstall()
  })

  beforeEach(function() {
    callback = jasmine.createSpy('sendResponse')
  })

  it('a spec', function() {

    asynFn('input string', callback)

    expect(jasmine.Ajax.requests.mostRecent().url).toBe('fake/path2')
    expect(callback).toHaveBeenCalled() // faild
  })
})

我在这里错过了什么?

【问题讨论】:

  • 请贴出被测代码并使用分号!
  • @Sonata 哦,对不起。因为我只想知道如何测试这种功能。所以我认为没有必要在这里发布所有内容。

标签: javascript ajax testing jasmine bdd


【解决方案1】:

问题是asynFn异步,并且在expect语句执行后调用的回调y。

认为你的测试就像历史。

  • 测试对象(描述)
  • asynFn 执行时(beforeEach)
  • 那么:应该调用一个方法或回调(它)

将您的代码更改为:

  beforeEach(function() {  
    callback = jasmine.createSpy('sendResponse');  
    asynFn('input string', callback);  
  });

 afterEach(function() {
    callback = null;
 });

  it('a spec', function() {
    expect(jasmine.Ajax.requests.mostRecent().url).toBe('fake/path2')
    expect(callback).toHaveBeenCalled() // faild
  })

如果第一个不起作用,试试这个:

 beforeEach(function(done) {  
      callback = jasmine.createSpy('sendResponse');  
      asynFn('input string', function() {
          callback();
          done(); //<-- This tells jasmine tha async beforeEach is finished
      });  
  });

【讨论】:

  • 我认为这意味着“在每个规范之前运行asynFn”。它如何确保在规范之前调用异步callback?。
  • 不错。这就是我刚刚修复它的方式。我以错误的方式使用done()。谢谢!公认。 :D
猜你喜欢
  • 1970-01-01
  • 2020-10-23
  • 1970-01-01
  • 2015-10-21
  • 2021-01-18
  • 1970-01-01
  • 2020-08-03
  • 1970-01-01
  • 2016-11-25
相关资源
最近更新 更多