更改jquery-mockjax在mocha测试中返回数据

时间:2016-02-12 11:24:48

标签: javascript mocha mockjax

我用mocha编写测试,检查从rest api轮询的更改状态是否正确呈现。是否可以更改模拟端点在测试过程中返回的内容?我已经尝试覆盖模拟的端点并使用var作为数据并更改它但不起作用。

使用覆盖:

it("should render correctly") {
  loadPage(done, {init: function() {
    testUtils.mockjax("/url", {"data": "data"})
  }, onload: function() {
    expect($$("#data")).to.be.visible()
    testUtils.mockjax("/url", {"data": ""})
    clock.tick(5000)
    expect($$("#data")).not.to.be.visible() # does not work
    ...
    done()
  }
}

使用变量:

it("should render correctly") {
  var data = {"data": "data"}
  loadPage(done, {init: function() {
    testUtils.mockjax("/url", data)
  }, onload: function() {
    expect($$("#data")).to.be.visible()
    data =  {"data": ""}
    clock.tick(5000)
    expect($$("#data")).not.to.be.visible() # does not work
    ...
    done()
  }
}

1 个答案:

答案 0 :(得分:0)

我会通过设置custom handler function与基本网址和数据匹配来实现此目的。您需要在测试块之前设置此模拟,但随后您可以检查传入的请求数据并确定是否匹配以及返回的内容:

$.mockjax(function(requestSettings) {
  if ( requestSettings.url === '...' ) {
    return {
      responseText: "foo"  // you can change this based on the incoming request
    };
  }
  // If you get here, there was no match
  return;
});