不知道如何用茉莉花测试这个异步函数

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

本文关键字:异步 函数 测试 何用 茉莉花 不知道      更新时间:2023-09-26
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异步的,并且在执行期望句子后调用的回调 y。

认为你的测试就像历史一样。

  • 被测试对象(描述(
  • 当 asynFn 被执行时(在每个之前(
  • then:应该调用方法或回调(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
      });  
  });