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

标签 javascript ajax testing jasmine bdd

asynFn(url, callback)

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

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

我尝试使用 jasmine-ajax 来 stub 请求,但是 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
      });  
  });

关于javascript - 不知道如何用 Jasmine 测试这个异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33869485/

相关文章:

android - 三星 galaxy 5 mp3 播放器作为开发设备

javascript - 合并对象并删除属性

javascript - 为什么我的表单只是刷新页面?

javascript - 如何设置信用卡到期日期输入字段的样式以包含空格和正斜杠?

javascript - 对象不支持属性或方法 'AddFill'

ajax - Thymeleaf:单击表行即可提交表单

javascript - Jest Mock - 将值插入测试文件

c# - xUnit 还是 NUnit?彼此有什么优点和缺点?

javascript - 为什么 Javascript 异常会使解释器处于不可预测的状态?

javascript - AJAX回调函数间歇性添加GET参数失败