我很难与Karma一起进行单元测试,我不知道如何进行单元测试,因为这是我的第一次。我使用的是AngularJS,单元测试是Karma。
事情是这样的:我使用服务获取客户的firstName,lastName和PhoneNumber以在我的表单中显示,并且它没有任何问题,但是当我尝试做的时候单元测试错误总是这样:
directionFormulation component should load customer profile FAILED
TypeError: Cannot read property 'firstName' of undefined
directionFormulation.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;
});
});
答案 0 :(得分:1)
您正在向控制器中注入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);
});
});
我想强调一些其他问题:
您的第一个测试断言expect(scope.addressForm).to.be.equal(component);
不会通过。 AddressFormController
是控制器的名称,控制器是组件的属性。
我不确定您的测试中bard
指的是什么,并且不确定appModule
是否是您的bard实例上的属性。以下是我的组件测试设置示例:https://gist.github.com/mcranston18/0ded29eca9a53efeb945736b0a053061
我建议使用此资源来学习有关测试组件控制器的更多信息:http://www.codelord.net/2017/01/09/unit-testing-angular-components-with-%24componentcontroller/