0

我坚持使用 Karma 进行单元测试,我不知道如何进行单元测试,因为这是我的第一次。我正在使用 AngularJS,单元测试是 Karma。

事情是这样的:我正在使用一项服务来获取要在我的表单中显示的客户的名字、姓氏和电话号码,并且它可以正常工作但是,当我尝试进行单元测试时,错误总是这:

directionFormulation component should load customer profile FAILED
        TypeError: Cannot read property 'firstName' of undefined

方向公式.js

  function directionFormulationController(event, customer, resolveLocation, order) {
    this.$onInit = onInit;
    this.input = this.input || {};

    function onInit() {
      loadCustomerData();
    }

    function loadCustomerData() {
      this.input.firstName = order.customer.firstName;
      this.input.lastName = order.customer.lastName;
      this.input.phoneNumber = order.customer.phoneNumber;

    }
  }
})();

单元测试:directionFormulation.spec.js:

  it('should load customer data', function () {
    var emptyFirstName = { firstName: 'something'};

    component.$onInit();
    order.customer.firstName = { firstName: 'Something'};
    order.customer.lastName = { lastName: 'Something' };
    order.customer.phoneNumber = { phoneNumber: 55555555};
    // component.input = {
    //   firstName: 'something',
    //   lastName: 'something',
    //   phoneNumber: 55555555
    // };

    component.loadCustomerData();
    $rootScope.$apply();
    component.input.firstName = newFirstName;

    expect(component.input.firstName).to.be.equal({firstName: 'something'});
    expect(component.input.lastName).to.be.not.empty;
    expect(component.input.phoneNumber).to.be.null;

  });
});
4

1 回答 1

2

您正在注入order您的控制器,因此您需要order为您的单元测试“模拟”:

describe('addressForm component', function () {
  var component;
  var scope;
  var order;

  beforeEach(function () {
    bard.appModule('shopping.address');
    bard.inject('$rootScope', '$componentController', '$q', 'resolveLocation', 'customer', 'event','order');
    order = {
      customer: {
        firstName: 'Joe',
        lastName: 'Smith',
        phoneNumber: '416-555-1234'
      }
    };
    scope = $rootScope.$new();
    component = $componentController('addressForm', { 
      $scope: scope,
      order: order
    });
  });

  it('should be attached to the scope', function () {
    expect(scope.addressForm).to.be.equal(component);
  });

  it('should load customer profile', function () {
    component.$onInit();
    component.loadCustomerProfile();

    expect(component.input.firstName).to.be.equal(order.customer.firstName);
    expect(component.input.lastName).to.be.equal(order.customer.lastName);
    expect(component.input.phoneNumber).to.be.equal(order.customer.phoneNumber);
  });
});

我想强调一些其他问题:

  1. 您的第一个测试断言expect(scope.addressForm).to.be.equal(component);不会通过。AddressFormController是控制器的名称,控制器是组件的属性。

  2. 我不确定bard您的测试中指的是什么,也不确定appModule您的吟游诗人实例是否是一个属性。这是我的组件测试设置示例:https ://gist.github.com/mcranston18/0ded29eca9a53efeb945736b0a053061

  3. 我会推荐这个资源来了解更多关于测试组件控制器的信息:http: //www.codelord.net/2017/01/09/unit-testing-angular-components-with-%24componentcontroller/

于 2017-09-28T15:48:11.817 回答