В настоящее время я новичок в модульном тестировании с использованием Jasmine, и меня попросили провести некоторое модульное тестирование на некоторых контроллерах и директивах.
У меня меньше проблем при выполнении модульного тестирования на контроллерах, и это довольно просто, но директивы намного сложнее, и в настоящее время они застряли в некоторых частях.
Итак, вот вся директива под названием "saleAlert.directive.js" - в стандартах ES6.
function saleAlertModal(alertService, basicUtils, $timeout) {
return {
restrict: 'E',
scope: true,
template: `
<div id="{{modalId}} class="modal fade" role="dialog" tabindex="-1">
...
<div class="modal-body">
<form name="saleAlertForm" data-ng-submit="submitted=true;emailAlert();" method="post" novalidate>
<div data-ng-if="isLoggedIn">
<label>Email:</label>
<p>{{emailAddress}}</p>
<input type="submit" value="Submit" class="btn btn-default" />
</div>
<div data-ng-if="!isLoggedIn">
<label>Email:</label>
<input type="email" class="form-control" data-ng-model="saleAlertForm.guestEmail" />
<input type="submit" value="Submit" class="btn btn-default" />
</div>
</form>
</div>
...
</div>
`,
link: (scope, element, attrs) => {
$timeout(() => {
external.refreshFunction();
});
scope.isLoggedIn = basicUtils.isLoggedIn();
let alertModal = '';
scope.saleConsent = attrs.saleConsentSigned !== 'undefined'
? attrs.saleConsentSigned
: false;
if (typeof attrs.componentId !== 'undefined') {
alertModal = attrs.componentId.replace(/ /g, '');
}
scope.modalId = attrs.componentId
? `saleAlertForUsers-${alertModal}`
: 'saleAlertForUsers';
scope.emailAddress = attrs.userEmail;
scope.emailAlert = () => {
let email;
if (!scope.emailAddress) {
email = scope.saleAlertForm.guestEmail;
} else {
email = scope.emailAddress;
}
if (email) {
alertService
.submitEmail(email, modalId)
.then(response => {
if (response && typeof scope.alertCallBack === 'function')
scope.alertCallBack();
});
}
};
element.on('hidden.bs.modal', () => {
scope.saleAlertForm.guestEmail = '';
});
}
}
}
Мой юнит тест выглядит так ...
describe('saleAlert.directive.js', () => {
let $scope;
let $compile;
let $timeout;
let basicUtils;
let elem;
let alertService;
beforeEach(() => {
module('shop');
inject($injector => {
$scope = $injector.get('$rootScope').$new();
$compile = $injector.get('$compile');
$timeout = $injector.get('$timeout');
basicUtils = $injector.get('basicUtils');
alertService = $injector.get('alertService');
});
const template = angular.element('<sale-alert-modal></sale-alert-modal>');
elem = $compile(template)($scope);
$scope.$apply();
});
it('expected to initialize all default settings', () => {
spyOn(external, 'refreshFunction');
$timeout.flush();
expect(external.refreshFunction).toHaveBeenCalled();
$scope.saleConsent = false;
// not sure how to get it from attrs dynamically
expect($scope.saleConsent).not.toBe(undefined);
});
it('Send sale alert notification to guest', () => {
spyOn(alertService, 'submitEmail');
$scope.emailAddress = '';
$scope.saleAlertForm = {
guestEmail: 'guest@email.com'
};
const email = $scope.saleAlertForm.guestEmail;
expect(email).toEqual($scope.saleAlertForm.guestEmail);
$scope.modalId = 'saleAlertForUsers';
expect($scope.modalId).not.toBeEmpty();
$scope.emailAlert();
expect(
alertService.submitEmail
).toHaveBeenCalledWith(email);
});});
СЕЙЧАС ... проблемы:
Как я могу получить динамические значения от attrs? В этом случае attrs.componentId и attrs.userEmail.
Всякий раз, когда я вызываю $ scope.emailAlert (); , выдается сообщение о том, что это не функция .
Я провел два модульных теста для IF-ELSE, но не был покрыт должным образом. Что-то я пропустил в тесте?
Спасибо и ценим любые отзывы! Ура!