本文整理汇总了TypeScript中angular.mock.inject方法的典型用法代码示例。如果您正苦于以下问题:TypeScript mock.inject方法的具体用法?TypeScript mock.inject怎么用?TypeScript mock.inject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类angular.mock
的用法示例。
在下文中一共展示了mock.inject方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: describe
describe('Service: applicationWriter', function () {
let applicationWriter: ApplicationWriter;
let taskExecutor: any;
let $q: ng.IQService;
beforeEach(
mock.module(
APPLICATION_WRITE_SERVICE
)
);
beforeEach(
mock.inject(function(_applicationWriter_: ApplicationWriter, _taskExecutor_: any, _$q_: ng.IQService) {
applicationWriter = _applicationWriter_;
taskExecutor = _taskExecutor_;
$q = _$q_;
})
);
describe('update an application', function () {
it('should execute task', function () {
spyOn(taskExecutor, 'executeTask');
const application: IApplicationAttributes = {
name: 'foo',
cloudProviders: [],
};
applicationWriter.updateApplication(application);
expect(taskExecutor.executeTask.calls.count()).toEqual(1);
});
it('should join cloud providers into a single string', function () {
let job: IJob = null;
spyOn(taskExecutor, 'executeTask').and.callFake((task: any) => job = task.job[0]);
const application: IApplicationAttributes = {
name: 'foo',
cloudProviders: ['titus', 'cf'],
};
applicationWriter.updateApplication(application);
expect(job).not.toBe(null);
expect(job.application.cloudProviders).toBe('titus,cf');
});
});
describe('delete an application', function () {
it('should execute task', function () {
spyOn(taskExecutor, 'executeTask').and.returnValue($q.when({}));
const application: IApplicationAttributes = {
name: 'foo',
};
applicationWriter.deleteApplication(application);
expect(taskExecutor.executeTask.calls.count()).toEqual(1);
});
});
});
示例2: describe
describe("SelectUploadModalInstanceCtrl", () => {
let ctrl: SelectUploadModalInstanceCtrl, fileUploaderService: FileUploaderService;
let $controller: IControllerService, $rootScope: IRootScopeService, $scope: IScope,
$uibModalInstance: { close: Function, dismiss: Function }, $q: IQService;
beforeEach(() => {
angular.mock.module(COMMON_MODULE);
angular.mock.module(PAGE_EDITOR_MODULE);
});
beforeEach(angular.mock.inject($injector => {
$controller = $injector.get("$controller");
$rootScope = $injector.get("$rootScope");
$q = $injector.get("$q");
$scope = $rootScope.$new(true);
fileUploaderService = $injector.get("FileUploaderService");
$uibModalInstance = {
close: () => {},
dismiss: () => {}
};
spyOn($uibModalInstance, "dismiss");
spyOn($uibModalInstance, "close");
}));
function initController(fieldName: string): void {
ctrl = $controller("SelectUploadModalInstanceCtrl", {
$scope: $scope,
$uibModalInstance: $uibModalInstance,
fieldName: fieldName
});
}
it("should instantiate correctly", () => {
spyOn(fileUploaderService, "getFiles").and.callFake(() => {
const deferred: IDeferred<Array<IRawFtpFile>> = $q.defer();
deferred.resolve([
{Filename: "file1.png", Size: 1, CreatedDate: "2017-11-01T01:40:00"},
{Filename: "file2.png", Size: 123, CreatedDate: "2017-12-01T01:40:00"}
]);
return deferred.promise;
});
initController("ThumbnailName");
expect(ctrl.files).toEqual([]);
expect($uibModalInstance.close).not.toHaveBeenCalled();
expect($uibModalInstance.dismiss).not.toHaveBeenCalled();
expect(ctrl.initState).toEqual({
isLoading: true, isSuccess: false
});
expect(SelectUploadModalInstanceCtrl.regexp).toEqual(/.(png|jpg|gif|jpeg)$/);
$scope.$digest();
expect(fileUploaderService.getFiles).toHaveBeenCalled();
expect(ctrl.files).toEqual([
{Filename: "file1.png", Size: 1, CreatedDate: moment("2017-11-01T01:40:00")},
{Filename: "file2.png", Size: 123, CreatedDate: moment("2017-12-01T01:40:00")}
]);
expect(ctrl.initState).toEqual({
isLoading: false, isSuccess: true
});
});
describe("#cancel", () => {
it("should cancel dialog", () => {
initController("ThumbnailName");
ctrl.cancel();
expect($uibModalInstance.dismiss).toHaveBeenCalled();
});
});
describe("#selectFile", () => {
it("should close dialog and return selected file", () => {
initController("ThumbnailName");
ctrl.selectFile({Filename: "test-file.png", Size: 1, CreatedDate: moment("2017-11-01T01:40:00")});
expect($uibModalInstance.close)
.toHaveBeenCalledWith({Filename: "test-file.png", Size: 1, CreatedDate: moment("2017-11-01T01:40:00")});
});
});
});
示例3: describe
describe('Component: ConfigSectionFooter', () => {
let $componentController: ng.IComponentControllerService,
$ctrl: ConfigSectionFooterController,
$q: ng.IQService,
$scope: ng.IScope;
const initializeController = (data: any) => {
$ctrl = $componentController('configSectionFooter', { $scope: null }, data) as ConfigSectionFooterController;
};
beforeEach(mock.module(CONFIG_SECTION_FOOTER));
beforeEach(
mock.inject(
(
_$componentController_: ng.IComponentControllerService,
_$q_: ng.IQService,
$rootScope: ng.IRootScopeService,
) => {
$scope = $rootScope.$new();
$componentController = _$componentController_;
$q = _$q_;
},
),
);
describe('revert', () => {
it('replaces contents of config with original config', () => {
const data = {
viewState: {
originalConfig: { exceptions: [] as any, enabled: false },
},
config: {
exceptions: [{ account: 'prod', region: 'us-east-1' }],
enabled: true,
grouping: 'app',
},
};
initializeController(data);
$ctrl.revert();
expect($ctrl.config).toEqual(data.config);
expect($ctrl.config).not.toBe(data.viewState.originalConfig);
expect(JSON.stringify($ctrl.config)).toBe(JSON.stringify(data.viewState.originalConfig));
});
});
describe('save', () => {
let data: any;
beforeEach(() => {
data = {
application: { name: 'deck', attributes: { accounts: ['prod'] } },
viewState: {
originalConfig: { exceptions: [], enabled: false },
originalStringVal: 'original',
saving: false,
saveError: false,
isDirty: true,
},
config: {
exceptions: [{ account: 'prod', region: 'us-east-1' }],
enabled: true,
grouping: 'app',
},
};
});
it('sets state to saving, saves, then sets flags appropriately', () => {
const viewState = data.viewState;
spyOn(ApplicationWriter, 'updateApplication').and.returnValue($q.when(null));
initializeController(data);
$ctrl.save();
expect(viewState.saving).toBe(true);
expect(viewState.isDirty).toBe(true);
$scope.$digest();
expect(viewState.saving).toBe(false);
expect(viewState.saveError).toBe(false);
expect(viewState.isDirty).toBe(false);
expect(viewState.originalConfig).toEqual(data.config);
expect(viewState.originalStringVal).toBe(JSON.stringify(data.config));
});
it('sets appropriate flags when save fails', () => {
const viewState = data.viewState;
spyOn(ApplicationWriter, 'updateApplication').and.returnValue($q.reject(null));
initializeController(data);
$ctrl.save();
expect(viewState.saving).toBe(true);
expect(viewState.isDirty).toBe(true);
$scope.$digest();
expect(viewState.saving).toBe(false);
expect(viewState.saveError).toBe(true);
expect(viewState.isDirty).toBe(true);
expect(viewState.originalConfig.enabled).toBe(false);
expect(viewState.originalStringVal).toBe('original');
//.........这里部分代码省略.........
示例4: describe
describe('Component: helpField', () => {
let helpContentsRegistry: HelpContentsRegistry,
$scope: ng.IScope,
$compile: ng.ICompileService;
const executeTest = (htmlString: string, expected: string, attr = 'uib-popover-html') => {
const helpField: JQuery = $compile(htmlString)($scope);
$scope.$digest();
expect(helpField.find('a').attr(attr)).toBe(expected);
};
const testContent = (htmlString: string, expected: string) => {
const helpField: JQuery = $compile(htmlString)($scope);
$scope.$digest();
expect(element(helpField.find('a')).scope()['$ctrl']['contents']['content']).toBe(expected);
};
beforeEach(() => {
mock.module(
HELP_FIELD_COMPONENT,
($provide: IProvideService) => {
$provide.constant('helpContents', {'aws.serverGroup.stack': 'expected stack help'});
});
});
beforeEach(mock.inject(($rootScope: ng.IRootScopeService,
_$compile_: ng.ICompileService,
_helpContentsRegistry_: HelpContentsRegistry) => {
helpContentsRegistry = _helpContentsRegistry_;
$compile = _$compile_;
$scope = $rootScope.$new();
}));
it('uses provided content if supplied', () => {
testContent('<help-field content="some content"></help-field>', 'some content');
});
it('uses key to look up content if supplied', () => {
testContent('<help-field key="aws.serverGroup.stack"></help-field>', 'expected stack help');
});
it('prefers overrides', () => {
spyOn(helpContentsRegistry, 'getHelpField').and.returnValue('override content');
testContent('<help-field key="aws.serverGroup.stack"></help-field>', 'override content');
});
it('uses fallback if key not present', () => {
testContent('<help-field key="nonexistent.key" fallback="the fallback"></help-field>', 'the fallback');
});
it('ignores key if content is defined', () => {
testContent('<help-field key="aws.serverGroup.stack" content="overridden!"></help-field>', 'overridden!');
});
it('ignores key and fallback if content is defined', () => {
testContent('<help-field key="aws.serverGroup.stack" fallback="will be ignored" content="overridden!"></help-field>', 'overridden!');
});
it('defaults position to "auto"', () => {
executeTest('<help-field content="overridden!"></help-field>', 'auto', 'popover-placement');
});
it('overrides position to "left"', () => {
executeTest('<help-field content="some content" placement="left"></help-field>', 'left', 'popover-placement');
});
});
示例5: describe
describe('Service: Cluster', function () {
beforeEach(
mock.module(CLUSTER_SERVICE, APPLICATION_MODEL_BUILDER)
);
let clusterService: ClusterService;
let clusterFilterModel: ClusterFilterModel;
let $http: IHttpBackendService;
let API: Api;
let application: Application;
function buildTask(config: {status: string, variables: {[key: string]: any}}) {
return {
status: config.status,
getValueFor: (key: string): any => {
return find(config.variables, { key: key }) ? find(config.variables, { key: key }).value : null;
}
};
}
beforeEach(mock.inject(($httpBackend: IHttpBackendService, _API_: Api, _clusterFilterModel_: ClusterFilterModel,
_clusterService_: ClusterService, applicationModelBuilder: ApplicationModelBuilder) => {
$http = $httpBackend;
API = _API_;
clusterService = _clusterService_;
clusterFilterModel = _clusterFilterModel_;
application = applicationModelBuilder.createApplication(
'app',
{ key: 'serverGroups' },
{ key: 'runningExecutions' },
{ key: 'runningTasks' }
);
application.getDataSource('serverGroups').data = [
{ name: 'the-target', account: 'not-the-target', region: 'us-east-1' },
{ name: 'the-target', account: 'test', region: 'not-the-target' },
{ name: 'the-target', account: 'test', region: 'us-east-1' },
{ name: 'not-the-target', account: 'test', region: 'us-east-1' },
{ name: 'the-source', account: 'test', region: 'us-east-1' }
];
}));
describe('lazy cluster fetching', () => {
it('switches to lazy cluster fetching if there are more than the on demand threshold for clusters', () => {
const clusters = Array(ClusterService.ON_DEMAND_THRESHOLD + 1);
$http.expectGET(API.baseUrl + '/applications/app/clusters').respond(200, { test: clusters });
$http.expectGET(API.baseUrl + '/applications/app/serverGroups?clusters=').respond(200, []);
let serverGroups: IServerGroup[] = null;
clusterService.loadServerGroups(application).then((result: IServerGroup[]) => serverGroups = result);
$http.flush();
expect(application.serverGroups.fetchOnDemand).toBe(true);
expect(serverGroups).toEqual([]);
});
it('does boring regular fetching when there are less than the on demand threshold for clusters', () => {
const clusters = Array(ClusterService.ON_DEMAND_THRESHOLD);
$http.expectGET(API.baseUrl + '/applications/app/clusters').respond(200, { test: clusters });
$http.expectGET(API.baseUrl + '/applications/app/serverGroups').respond(200, []);
let serverGroups: IServerGroup[] = null;
clusterService.loadServerGroups(application).then((result: IServerGroup[]) => serverGroups = result);
$http.flush();
expect(application.serverGroups.fetchOnDemand).toBe(false);
expect(serverGroups).toEqual([]);
});
it('converts clusters parameter to q and account params when there are fewer than 251 clusters', () => {
spyOn(clusterFilterModel.asFilterModel, 'applyParamsToUrl').and.callFake(() => {});
const clusters = Array(250);
clusterFilterModel.asFilterModel.sortFilter.clusters = { 'test:myapp': true };
$http.expectGET(API.baseUrl + '/applications/app/clusters').respond(200, { test: clusters });
$http.expectGET(API.baseUrl + '/applications/app/serverGroups').respond(200, []);
let serverGroups: IServerGroup[] = null;
clusterService.loadServerGroups(application).then((result: IServerGroup[]) => serverGroups = result);
$http.flush();
expect(application.serverGroups.fetchOnDemand).toBe(false);
expect(clusterFilterModel.asFilterModel.sortFilter.filter).toEqual('clusters:myapp');
expect(clusterFilterModel.asFilterModel.sortFilter.account.test).toBe(true);
});
});
describe('health count rollups', () => {
it('aggregates health counts from server groups', () => {
application.serverGroups.data = [
{ cluster: 'cluster-a', name: 'cluster-a-v001', account: 'test', region: 'us-east-1', instances: [], instanceCounts: { total: 1, up: 1 } },
{ cluster: 'cluster-a', name: 'cluster-a-v001', account: 'test', region: 'us-west-1', instances: [], instanceCounts: { total: 2, down: 2 } },
{ cluster: 'cluster-b', name: 'cluster-b-v001', account: 'test', region: 'us-east-1', instances: [], instanceCounts: { total: 1, starting: 1 } },
{ cluster: 'cluster-b', name: 'cluster-b-v001', account: 'test', region: 'us-west-1', instances: [], instanceCounts: { total: 1, outOfService: 1 } },
{ cluster: 'cluster-b', name: 'cluster-b-v002', account: 'test', region: 'us-west-1', instances: [], instanceCounts: { total: 2, unknown: 1, outOfService: 1 } },
];
const clusters = clusterService.createServerGroupClusters(application.serverGroups.data);
const cluster0counts: IInstanceCounts = clusters[0].instanceCounts;
const cluster1counts: IInstanceCounts = clusters[1].instanceCounts;
expect(clusters.length).toBe(2);
expect(cluster0counts.total).toBe(3);
expect(cluster0counts.up).toBe(1);
expect(cluster0counts.down).toBe(2);
expect(cluster0counts.starting).toBe(0);
expect(cluster0counts.outOfService).toBe(0);
expect(cluster0counts.unknown).toBe(0);
//.........这里部分代码省略.........
示例6: describe
describe('Travis Execution Details Controller:', () => {
let $scope: IScope, $ctrl: IControllerService;
beforeEach(mock.module(TRAVIS_EXECUTION_DETAILS_CONTROLLER));
beforeEach(
mock.inject(($controller: IControllerService, $rootScope: IRootScopeService) => {
$ctrl = $controller;
$scope = $rootScope.$new();
}),
);
const initializeController = (stage: any): TravisExecutionDetailsCtrl => {
$scope.stage = stage;
return $ctrl(TravisExecutionDetailsCtrl, {
$scope,
executionDetailsSectionService: { synchronizeSection: ({}, fn: () => any) => fn() },
});
};
describe('getting failure message', () => {
it('should count number of failing tests', () => {
const stage = {
context: {
buildInfo: {
testResults: [{ failCount: 0 }, { failCount: 3 }, { failCount: 2 }],
},
},
};
const controller = initializeController(stage);
expect(controller.failureMessage).toBe('5 tests failed.');
});
it('should fall back to "build failed" message when no failed tests found, but result is "FAILURE"', () => {
let stage = {
context: {
buildInfo: {
result: 'FAILURE',
testResults: [] as any,
},
},
};
let controller = initializeController(stage);
expect(controller.failureMessage).toBe('Build failed.');
stage = {
context: {
buildInfo: {
result: 'FAILURE',
testResults: [{ failCount: 0 }],
},
},
};
controller = initializeController(stage);
expect(controller.failureMessage).toBe('Build failed.');
});
it('should set failureMessage to undefined when not failing', function() {
const controller = initializeController({});
expect(controller.failureMessage).toBeUndefined();
});
});
});
示例7: describe
describe('Service: accountService', () => {
let $http: ng.IHttpBackendService;
let cloudProviderRegistry: CloudProviderRegistry;
let API: Api;
let accountService: AccountService;
beforeEach((mock.module(API_SERVICE, ACCOUNT_SERVICE)));
beforeEach(
mock.inject(
function ($httpBackend: ng.IHttpBackendService,
_cloudProviderRegistry_: CloudProviderRegistry,
_API_: Api,
_accountService_: AccountService) {
$http = $httpBackend;
cloudProviderRegistry = _cloudProviderRegistry_;
API = _API_;
accountService = _accountService_;
}));
afterEach(SETTINGS.resetToOriginal);
it('should filter the list of accounts by provider when supplied', () => {
$http.expectGET(`${API.baseUrl}/credentials`).respond(200, [
{name: 'test', type: 'aws'},
{name: 'prod', type: 'aws'},
{name: 'prod', type: 'gce'},
{name: 'gce-test', type: 'gce'},
]);
let accounts: IAccount[] = null;
accountService.listAccounts('aws').then((results: IAccount[]) => accounts = results);
$http.flush();
expect(accounts.length).toBe(2);
expect(accounts.map((account: IAccount) => account.name)).toEqual(['test', 'prod']);
});
describe('getAllAccountDetailsForProvider', () => {
it('should return details for each account', function () {
$http.expectGET(API.baseUrl + '/credentials').respond(200, [
{name: 'test', type: 'aws'},
{name: 'prod', type: 'aws'},
]);
$http.expectGET(API.baseUrl + '/credentials/test').respond(200, {a: 1});
$http.expectGET(API.baseUrl + '/credentials/prod').respond(200, {a: 2});
let details: any = null;
accountService.getAllAccountDetailsForProvider('aws').then((results: any) => {
details = results;
});
$http.flush();
expect(details.length).toBe(2);
expect(details[0].a).toBe(1);
expect(details[1].a).toBe(2);
});
it('should fall back to an empty array if an exception occurs when listing accounts', () => {
$http.expectGET(`${API.baseUrl}/credentials`).respond(429, null);
let details: any[] = null;
accountService.getAllAccountDetailsForProvider('aws').then((results: any[]) => {
details = results;
});
$http.flush();
expect(details).toEqual([]);
});
it('should fall back to an empty array if an exception occurs when getting details for an account', () => {
$http.expectGET(`${API.baseUrl}/credentials`).respond(200, [
{name: 'test', type: 'aws'},
{name: 'prod', type: 'aws'},
]);
$http.expectGET(API.baseUrl + '/credentials/test').respond(500, null);
$http.expectGET(API.baseUrl + '/credentials/prod').respond(200, {a: 2});
let details: any = null;
accountService.getAllAccountDetailsForProvider('aws').then((results: any) => {
details = results;
});
$http.flush();
expect(details).toEqual([]);
});
});
describe('listProviders', () => {
let registeredProviders: string[];
beforeEach(() => {
registeredProviders = ['aws', 'gce', 'cf'];
$http.whenGET(`${API.baseUrl}/credentials`).respond(200,
[{type: 'aws'}, {type: 'gce'}, {type: 'cf'}]
//.........这里部分代码省略.........
示例8: describe
describe('API Service', function() {
let $httpBackend: ng.IHttpBackendService;
let baseUrl: string;
beforeEach(
mock.inject(function(_$httpBackend_: ng.IHttpBackendService) {
$httpBackend = _$httpBackend_;
baseUrl = SETTINGS.gateUrl;
}),
);
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
describe('validate response content-type header', function() {
it('responses with non-"application/json" content types should trigger a reauthentication request and reject', function() {
spyOn(AuthenticationInitializer, 'reauthenticateUser').and.callFake(noop);
$httpBackend
.expectGET(`${baseUrl}/bad`)
.respond(200, '<html>this is the authentication page</html>', { 'content-type': 'text/html' });
let rejected = false;
API.one('bad')
.get()
.then(noop, () => (rejected = true));
$httpBackend.flush();
expect((AuthenticationInitializer.reauthenticateUser as Spy).calls.count()).toBe(1);
expect(rejected).toBe(true);
});
it('string responses starting with <html should trigger a reauthentication request and reject', function() {
spyOn(AuthenticationInitializer, 'reauthenticateUser').and.callFake(noop);
$httpBackend.expectGET(`${baseUrl}/fine`).respond(200, 'this is fine');
let rejected = false;
let succeeded = false;
API.one('fine')
.get()
.then(() => (succeeded = true), () => (rejected = true));
$httpBackend.flush();
expect((AuthenticationInitializer.reauthenticateUser as Spy).calls.count()).toBe(0);
expect(rejected).toBe(false);
expect(succeeded).toBe(true);
});
it('object and array responses should pass through', function() {
spyOn(AuthenticationInitializer, 'reauthenticateUser').and.callFake(noop);
let rejected = false;
let succeeded = false;
$httpBackend.expectGET(`${baseUrl}/some-array`).respond(200, []);
API.one('some-array')
.get()
.then(() => (succeeded = true), () => (rejected = true));
$httpBackend.flush();
expect((AuthenticationInitializer.reauthenticateUser as Spy).calls.count()).toBe(0);
expect(rejected).toBe(false);
expect(succeeded).toBe(true);
// verify object responses
rejected = false;
succeeded = false;
$httpBackend.expectGET(`${baseUrl}/some-object`).respond(200, {});
API.one('some-object')
.get()
.then(() => (succeeded = true), () => (rejected = true));
$httpBackend.flush();
expect((AuthenticationInitializer.reauthenticateUser as Spy).calls.count()).toBe(0);
expect(rejected).toBe(false);
expect(succeeded).toBe(true);
});
});
describe('creating the config and testing the chaining functions without parameters', () => {
let expected: ng.IRequestConfig;
beforeEach(() => {
expected = {
method: '',
url: '',
};
});
describe('creating the config with "one" function', function() {
it('missing url should create a default config with the base url', function() {
const result = API.one();
expected.url = baseUrl;
expect(result.config).toEqual(expected);
});
it('single url should create a default config with the base url', function() {
const result = API.one('foo');
expected.url = `${baseUrl}/foo`;
expect(result.config).toEqual(expected);
});
//.........这里部分代码省略.........
示例9: describe
describe('Task Data Source', function () {
let application: Application,
taskReader: TaskReader,
$scope: any,
applicationModelBuilder: any,
applicationDataSourceRegistry: any,
$q: ng.IQService;
beforeEach(
mock.module(
require('./task.dataSource').name,
TASK_READ_SERVICE,
APPLICATION_DATA_SOURCE_REGISTRY,
APPLICATION_MODEL_BUILDER
));
beforeEach(
mock.inject(function (_taskReader_: TaskReader, _$q_: any, $rootScope: any,
_applicationModelBuilder_: any, _applicationDataSourceRegistry_: any) {
$q = _$q_;
$scope = $rootScope.$new();
taskReader = _taskReader_;
applicationModelBuilder = _applicationModelBuilder_;
applicationDataSourceRegistry = _applicationDataSourceRegistry_;
})
);
function configureApplication() {
applicationDataSourceRegistry.registerDataSource({ key: 'serverGroups' });
application = applicationModelBuilder.createApplication('app', applicationDataSourceRegistry.getDataSources());
application.refresh();
application.getDataSource('tasks').activate();
$scope.$digest();
}
describe('loading tasks', function () {
beforeEach(function () {
spyOn(taskReader, 'getRunningTasks').and.returnValue($q.when([]));
});
it('loads tasks and sets appropriate flags', function () {
spyOn(taskReader, 'getTasks').and.returnValue($q.when([]));
configureApplication();
expect(application.getDataSource('tasks').loaded).toBe(true);
expect(application.getDataSource('tasks').loading).toBe(false);
expect(application.getDataSource('tasks').loadFailure).toBe(false);
});
it('sets appropriate flags when task load fails', function () {
spyOn(taskReader, 'getTasks').and.returnValue($q.reject(null));
configureApplication();
expect(application.getDataSource('tasks').loaded).toBe(false);
expect(application.getDataSource('tasks').loading).toBe(false);
expect(application.getDataSource('tasks').loadFailure).toBe(true);
});
});
describe('reload tasks', function () {
beforeEach(function () {
spyOn(taskReader, 'getRunningTasks').and.returnValue($q.when([]));
});
it('reloads tasks and sets appropriate flags', function () {
let nextCalls = 0;
spyOn(taskReader, 'getTasks').and.returnValue($q.when([]));
configureApplication();
application.getDataSource('tasks').onRefresh($scope, () => nextCalls++);
expect(application.getDataSource('tasks').loaded).toBe(true);
expect(application.getDataSource('tasks').loading).toBe(false);
expect(application.getDataSource('tasks').loadFailure).toBe(false);
application.getDataSource('tasks').refresh();
expect(application.getDataSource('tasks').loading).toBe(true);
$scope.$digest();
expect(application.getDataSource('tasks').loaded).toBe(true);
expect(application.getDataSource('tasks').loading).toBe(false);
expect(application.getDataSource('tasks').loadFailure).toBe(false);
expect(nextCalls).toBe(1);
});
it('sets appropriate flags when task reload fails; subscriber is responsible for error checking', function () {
spyOn(taskReader, 'getTasks').and.returnValue($q.reject(null));
let errorsHandled = 0,
successesHandled = 0;
configureApplication();
application.getDataSource('tasks').onRefresh($scope, () => successesHandled++, () => errorsHandled++);
application.getDataSource('tasks').refresh();
$scope.$digest();
expect(application.getDataSource('tasks').loading).toBe(false);
expect(application.getDataSource('tasks').loadFailure).toBe(true);
application.getDataSource('tasks').refresh();
$scope.$digest();
//.........这里部分代码省略.........
示例10: describe
describe("CaEnvironmentIndicatorCtrl", () => {
let ctrl: CaEnvironmentIndicatorCtrl, dataService: DataService, caLondonAppConfig: ICALondonAppConfig,
caEnvironmentIndicatorService: CAEnvironmentIndicatorService;
let $controller: IControllerService, $rootScope: IRootScopeService, $scope: IScope, $timeout: ITimeoutService, $q: IQService;
beforeEach(() => angular.mock.module(CORE_MODULE));
beforeEach(angular.mock.inject($injector => {
$timeout = $injector.get("$timeout");
$controller = $injector.get("$controller");
$rootScope = $injector.get("$rootScope");
$q = $injector.get("$q");
$scope = $rootScope.$new(true);
dataService = $injector.get("DataService");
caLondonAppConfig = $injector.get("caLondonAppConfig");
caLondonAppConfig.API_URL = "https://myurl.com/";
spyOn(dataService, "getData").and.callFake(() => {
const deferred: IDeferred<any> = $q.defer();
deferred.resolve({
Environment: "ApiDebugPromise",
Version: "3.7.0"
});
return deferred.promise;
});
caEnvironmentIndicatorService = $injector.get("CAEnvironmentIndicatorService");
caEnvironmentIndicatorService.environment = "ApiDebug";
caEnvironmentIndicatorService.version = "1.2.3";
caLondonAppConfig.UI_ENVIRONMENT = "UIDebug";
}));
function initController(): void {
ctrl = $controller("CaEnvironmentIndicatorCtrl", {
$scope: $scope
});
}
it("should instantiate", () => {
initController();
expect(ctrl).toBeDefined();
expect(ctrl.showAlert).toEqual(true);
expect(ctrl.apiEnvironment).toEqual("ApiDebug");
expect(ctrl.uiEnvironment).toEqual("UIDebug");
});
it("should attempt reload of api property if not loaded", () => {
caEnvironmentIndicatorService.environment = undefined;
initController();
expect(ctrl.showAlert).toEqual(false);
expect(ctrl.apiEnvironment).toBeUndefined();
$timeout.flush();
expect(ctrl.showAlert).toEqual(true);
expect(ctrl.apiEnvironment).toEqual("ApiDebugPromise");
});
describe("#alertClass", () => {
beforeEach(() => {
initController();
});
it("should return Danger if environments are both Debug", () => {
ctrl.apiEnvironment = "Debug";
ctrl.uiEnvironment = "Debug";
expect(ctrl.alertClass()).toEqual({ alert: true, "alert-danger": true });
expect(ctrl.showAlert).toEqual(true);
});
it("should return Warning if environments are both Dev", () => {
ctrl.apiEnvironment = "Dev";
ctrl.uiEnvironment = "Dev";
expect(ctrl.alertClass()).toEqual({ alert: true, "alert-warning": true });
expect(ctrl.showAlert).toEqual(true);
});
it("should return Success if environments are both Test", () => {
ctrl.apiEnvironment = "Test";
ctrl.uiEnvironment = "Test";
expect(ctrl.alertClass()).toEqual({ alert: true, "alert-success": true });
expect(ctrl.showAlert).toEqual(true);
});
it("should not show alert if environments are both Release", () => {
ctrl.apiEnvironment = "Release";
ctrl.uiEnvironment = "Release";
expect(ctrl.alertClass()).toEqual({});
expect(ctrl.showAlert).toEqual(false);
});
it("should return Info if environments are mismatched", () => {
//.........这里部分代码省略.........