Search code examples
javascriptjqueryjasminejasmine-jquery

Using jquery selectors in an expect in jasmine


I've noticed that you when writing jasmine unit tests usually the format is:

expect($('#foo')).toHaveValue('#bar');

But recently I've discovered by accident that the following also works:

expect('#foo').toHaveValue('#bar');

Is this expected behaviour? This seems like a better way to write my expects but I have never seen this notation before and I want to be sure I am not abusing something.

Could anyone confirm this is the way to go or direct me to any documentation of this?

(I am using the jasmine jquery library)


Solution

  • I've played around a bit with that. Looks like it really does work, having some peculiarities, though.

    I've tried things like:

    expect('.search-form').toBeInDOM();
    expect('.search-form').toEqual('div');
    expect('.search-form').toContainElement('.search-form__footer');
    
    • the first one passes and truely fails when changing to .not.toBeInDOM();
    • the third one looks same -- it truely fails is changing to some bad selector for toContainElement
    • the second one is a problem because of ambiguity: '.search-form' can be treated both as string and a selector.

    Had a very brief look into source code, it looks likes matchers really do resolve expectation actual as a selector (example from):

    toBeInDOM: function () {
        return {
          compare: function (actual) {
            return { pass: $.contains(document.documentElement, $(actual)[0]) }
          }
        }
      },
    

    Although I could not find any sign of such abilities in their docs, too. Still, source code is source code ))) and it says what it says. And now it says it will treat the actual for expect as a selector.