【问题标题】:Not getting json response from unit test in karma jasmine in angularjs?没有从angularjs中业力茉莉的单元测试中获得json响应?
【发布时间】:2016-08-26 04:16:09
【问题描述】:
describe('getEmployeeDetails', function () {
var getEmployeeDetails, httpBackend;
//2.
beforeEach(function () {
    //3. load the module.
    module('nodeApp');

    // 4. get your service, also get $httpBackend
    // $httpBackend will be a mock.
    inject(function ($httpBackend, _getEmployeeDetails_) {
        getEmployeeDetails = _getEmployeeDetails_;
        httpBackend = $httpBackend;
    });
});

// 5. make sure no expectations were missed in your tests.
afterEach(function () {
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
});

//6.
it('ServiceTestSpec', function () {

    var returnData = {};

    //7. expectGET to make sure this is called once.
    httpBackend.expectGET("/employee/getEmployeeDetails").respond(returnData);

    //8. make the call.
    var returnedPromise = getEmployeeDetails.getEmployees();

    //9. set up a handler for the response, that will put the result
    // into a variable in this scope for you to test.
    var result;
    returnedPromise.then(function (response) {
        result = response.data;
    });

    //10. flush the backend to "execute" the request to do the expectedGET assertion.
    httpBackend.flush();

    //11. check the result.
    expect(result).toEqual(returnData);
});

这是我用 karma jasmine 编写的单元测试。 我正在 chrome 控制台中调试这个单元测试,但我得到“响应”对象空白。

我使用 $httpBackend 来伪造 HTTP 请求。这是我没有得到响应对象的原因吗?

但是我的测试通过了成功。 还有一件事是:这是好的做法吗?用angularJS写单元测试?

【问题讨论】:

    标签: angularjs node.js karma-runner karma-jasmine


    【解决方案1】:

    默认情况下,angularJS Karma 测试会阻止 $http 请求,因此您不会收到 json 响应。 要获得响应,请使用.passThrough(),而不是附加.respond(yourFakeResponse),这将发出预期的请求。

    但是,在我看来,这并不是一个真正的好习惯,因为测试现在依赖于外部资源,即在这种情况下是您的 json 文件,或任何其他外部 API 等。因为外部资源中的问题也可能会破坏测试,这不再属于单元测试的范畴,而更像是一个集成测试。

    最好像您所做的那样调用一个假响应对象,同时设置一个单独的常量或服务文件来集中管理您的模拟响应数据。

    【讨论】:

      猜你喜欢
      • 2014-03-12
      • 2015-04-01
      • 2015-10-23
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      • 2017-05-26
      • 1970-01-01
      相关资源
      最近更新 更多