【问题标题】:How to assert that a backend endpoint has been called?如何断言后端端点已被调用?
【发布时间】:2015-03-18 14:12:22
【问题描述】:

我正在使用 Protractor 构建 Angular 应用程序的 E2E 测试。后端 HTTP 服务被 $httpBackend 模拟。到目前为止,测试看起来是这样的:

describe('foo', function () {
  it('bar', function () {
    var backendMockModule = function () {
      angular
        .module('backendMock', [])
        .run(['$httpBackend', function ($httpBackend) {
          $httpBackend.whenPUT('http://localhost:8080/services/foo/bar')
            .respond(function (method, url, data, header) {
              return [200, {}, {}];
            });
        }]);
    };
    browser.addMockModule('backendMock', backendMockModule);

    browser.get('http://localhost:8001/#/foo/bar');

    element(by.id('baz')).click();

    // here I would like to assert that the Angular app issued a PUT to '/foo/bar' with data = {...}
  });
});

测试比这更详细一点,它测试界面和其他东西的乐观更新。但我认为这与这个问题无关,所以我删除了其他部分。测试本身运行良好,我能够检查界面上的元素是否符合预期。我没有发现的是:

如何断言已使用正确的数据、方法、标头等调用后端 HTTP 端点?

我试过这样做(添加hasBeenCalled变量):

describe('foo', function () {
  it('bar', function () {
    var hasBeenCalled = false;

    var backendMockModule = function () {
      angular
        .module('backendMock', [])
        .run(['$httpBackend', function ($httpBackend) {
          $httpBackend.whenPUT('http://localhost:8080/services/foo/bar')
            .respond(function (method, url, data, header) {
              hasBeenCalled = true;
              return [200, {}, {}];
            });
        }]);
    };
    browser.addMockModule('backendMock', backendMockModule);

    browser.get('http://localhost:8001/#/foo/bar');

    element(by.id('baz')).click();

    expect(hasBeenCalled).toBeTruthy();
  });
});

但它不起作用。我不知道量角器是如何进行测试的,但我想它会在调用addMockModule 中将函数的序列化版本发送到浏览器,而不是在与网页相同的进程中运行测试,所以我'无法在测试和浏览器之间共享状态(附带问题:正确吗?)。

【问题讨论】:

    标签: javascript angularjs unit-testing protractor angularjs-e2e


    【解决方案1】:

    在expect(...)...之前需要$httpBackend.flush()...

    【讨论】:

      猜你喜欢
      • 2023-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      相关资源
      最近更新 更多