不知道如何用 Jasmine 测试这个异步函数

Don't know how to test this asyn function with Jasmine

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
  })
})

我在这里错过了什么?

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

认为你的考试像历史一样。

  • 正在测试的对象(描述)
  • asynFn执行时(beforeEach)
  • 然后:应该调用方法或回调 (it)

将您的代码更改为:

  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
      });  
  });