AngularJS + Jasmine: Comparing objects

前端 未结 6 1650
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 03:18

I\'m just starting out writing tests for my AngularJS app and am doing so in Jasmine.

Here are the relevant code snippets

ClientController:

\         


        
6条回答
  •  庸人自扰
    2020-12-15 04:02

    I just had a similar problem and implemented a custom matcher as follows, based on many approaches:

    beforeEach(function() {
      this.addMatchers({
        toBeSimilarTo: function(expected) {
          function buildObject(object) {
            var built = {};
            for (var name in object) {
              if (object.hasOwnProperty(name)) {
                built[name] = object[name];
              }
            }
            return built;
          }
    
          var actualObject = buildObject(this.actual);
          var expectedObject = buildObject(expected);
          var notText = this.isNot ? " not" : "";
    
          this.message = function () {
            return "Expected " + actualObject + notText + " to be similar to " + expectedObject;
          }
    
          return jasmine.getEnv().equals_(actualObject, expectedObject);
    
        }
      });
    });
    

    and then used this way:

    it("gets the right data", function() {
      expect(scope.jobs[0]).toBeSimilarTo(myJob);
    });
    

    Of course, it's a very simple matcher and doesn't support many cases, but I didn't need anything more complex than that. You can wrap the matchers in a config file.

    Check this answer for a similar implementation.

提交回复
热议问题