Oam Psy
Oam Psy

Reputation: 8663

Unit Testing How to access object property

I have a simple angular service:

app.service('myService', function() {

    this.getMsg = function (status, data) {

        var errMsg = '';

        if (status.toString()[0] == 4) {

            if ((data.message.indexOf("3 tries left") > -1) || (data.message.indexOf("2 tries left")) > -1){
                errMsg = "Opps, try later";
            }
            else {
                errMsg = "Please try again.";
            }
        }

        if (status.toString()[0] == 5) {
            errMsg = "Under Construction";
        }

        return errMsg;
    };
});

And I have wrote a test that ensures my getMsg function exists, however when I try to test the function, I get an error:

TypeError: data.message is undefined

Test:

describe('myService', function (){
  var myService;

  beforeEach(function (){

    module('myApp');

    inject(function(_myService_) {
      myService = _myService_;
    });
  });

  it('should have an getMsg function', function () { 
    expect(angular.isFunction(myService.getMsg)).toBe(true);
  });

  it('test fucntion', function (){
    var result = myService.getMsg(400, "some text to test");
    expect(result).toBe('bar!!!');
  });
});

Upvotes: 0

Views: 518

Answers (1)

Tibos
Tibos

Reputation: 27823

There is a difference between the way you expected the getMsg function to behave when you wrote the function and the way you expected it to behave when you tested it.

When you wrote it, you expected the second parameter to be an object which has a message property which is a string.

When you tested it, you expected the second parameter to be a string.

If your function is correct, you should change this line

var result = myService.getMsg(400, "some text to test");

to

var result = myService.getMsg(400, { message : "some text to test"});

Upvotes: 2

Related Questions