Search code examples
ajaxangularkarma-jasminebloodhoundbootstrap-tags-input

testing remote option for bloodhound with jasmine


I am working with https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/ to handle tags selection. That library uses bloodhound as the suggestion engine as shown in those examples.

In my angular2+ component tests, I am calling $el.focus(). $el is the input field I am using bootstrap-tagsinput on.

After the focus() event, I am calling timeouts of 1000 Milliseconds then I stubbing the ajax response as like this...

const request = jasmine.Ajax.requests.mostRecent();
request.respondWith(response);

The problem is, the tests are flaky in CircleCI and they pass locally(When using the browser only). in CI, They sometimes work and sometimes they don't. When I remove the timeouts(Which I would love to do away with) the tests don't work at all. This is because calling jasmine.Ajax.requests.mostRecent() returns undefined.

When I try to run the entire angular suite in terminal locally, the tests are failing, all the time. It feels like the ajax call by bloodhound is not being triggered at all or it gets swallowed by something else. Here is my test suit in full...

describe('Component', () => {
  let $el: JQuery;

  beforeEach(() => {
    jasmine.Ajax.install();
  });

  afterEach(() => {
    jasmine.Ajax.uninstall();
  });

  describe('filters with different roles', () => {
    it('should load and select project filter optionsr', () => {
      setCurrentUser({ role: ['some role'] });
      $el = instantiateComponent();

      const response = {
        responseText: '[{ "id":1, "name":"Nice name"}]',
        status: 200,
      };

      $el.find('input[placeholder="Project(s)"]').focus();

      runTimeouts(1000)

      // the focus triggered an Ajax request to /projects.json
      const request = jasmine.Ajax.requests.mostRecent();

      request.respondWith(response); // this fails because request sometimes is undefined.

     // I then test for UI changes here
    });

  });
});

What am I doing wrong? Is there a way to do this without timeouts that ensure consistency in the tests?


Solution

  • Turns out using$elemet.focus() or $element.click() was the problem. It worked by using ngClick() instead. $el.find('input[placeholder="Project(s)"]').ngClick();. Not sure why it is like that though.