简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM