Testing a service function POST response with Jasmine

两盒软妹~` 提交于 2019-12-06 04:15:53

This line is why you get an empty object as your response:

httpBackend.expect('POST', url + '/api/AuthService/signIn', dataObj)
        .respond({});

To give the response you want just add the following:

httpBackend.expect('POST', url + '/api/AuthService/signIn', dataObj)
            .respond({"login": { "user": "Test_User", "time": 54935934593 }, "outputHead": { "token": asjfjj234kfAd }});

See the documentation for more information.

Brandon Short

The main thing to remember is that you are mocking the backend service request, and not actually hitting the service. This is done with this statement:

httpBackend.expect('POST', url + '/api/AuthService/signIn', dataObj)
    .respond({});

What this says is for a POST that matches this url, fake a response with an empty object. If you want to fake a response that looks like your real response, you can simply set up that object in the .response function call.

Example:

.respond({login:myuser,authenticated=true}).

If you are trying to test your backend API, you will want to look into other testing frameworks, such as protractor;

You are mocking your backend with the $httpBackend service, that means, there won't be a real request, but when you post to url + '/api/AuthService/signIn' your mocked backend will respond with an empty object (.respond({})) You should respond with the same kind of data that your real backend gives back. The main point is, you have the control of what cases are you want to cover with your test. So you can write API response for failed or successful logins

if you do a request in postman, that is going to use your real backend, that is the difference

more info: https://docs.angularjs.org/api/ngMock/service/$httpBackend http://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-karma.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!