Changing jquery-mockjax return data in the middle of a mocha test

128 Views Asked by At

I'm writing tests with mocha that check that a changing state polled from a rest api is rendered correctly. Is it possible to change what the mocked endpoint returns in the middle of the test? I've tried overriding the mocked endpoint and using var as the data and changing it but neither works.

With override:

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

With variable:

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

There are 1 best solutions below

0
On

I would do this by setting up a custom handler function versus the basic url and data matching. You would need to set up this mock before your test block, but then you could inspect the incoming request data and determine whether to match and what to return:

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