Best JavaScript code snippet using ng-mocks
apply-disable-directives.js
Source:apply-disable-directives.js
1/**2 * @fileoverview A module that filters reported problems based on `eslint-disable` and `eslint-enable` comments3 * @author Teddy Katz4 */5"use strict";6const lodash = require("lodash");7/**8 * Compares the locations of two objects in a source file9 * @param {{line: number, column: number}} itemA The first object10 * @param {{line: number, column: number}} itemB The second object11 * @returns {number} A value less than 1 if itemA appears before itemB in the source file, greater than 1 if12 * itemA appears after itemB in the source file, or 0 if itemA and itemB have the same location.13 */14function compareLocations(itemA, itemB) {15 return itemA.line - itemB.line || itemA.column - itemB.column;16}17/**18 * This is the same as the exported function, except that it19 * doesn't handle disable-line and disable-next-line directives, and it always reports unused20 * disable directives.21 * @param {Object} options options for applying directives. This is the same as the options22 * for the exported function, except that `reportUnusedDisableDirectives` is not supported23 * (this function always reports unused disable directives).24 * @returns {{problems: Problem[], unusedDisableDirectives: Problem[]}} An object with a list25 * of filtered problems and unused eslint-disable directives26 */27function applyDirectives(options) {28 const problems = [];29 let nextDirectiveIndex = 0;30 let currentGlobalDisableDirective = null;31 const disabledRuleMap = new Map();32 // enabledRules is only used when there is a current global disable directive.33 const enabledRules = new Set();34 const usedDisableDirectives = new Set();35 for (const problem of options.problems) {36 while (37 nextDirectiveIndex < options.directives.length &&38 compareLocations(options.directives[nextDirectiveIndex], problem) <= 039 ) {40 const directive = options.directives[nextDirectiveIndex++];41 switch (directive.type) {42 case "disable":43 if (directive.ruleId === null) {44 currentGlobalDisableDirective = directive;45 disabledRuleMap.clear();46 enabledRules.clear();47 } else if (currentGlobalDisableDirective) {48 enabledRules.delete(directive.ruleId);49 disabledRuleMap.set(directive.ruleId, directive);50 } else {51 disabledRuleMap.set(directive.ruleId, directive);52 }53 break;54 case "enable":55 if (directive.ruleId === null) {56 currentGlobalDisableDirective = null;57 disabledRuleMap.clear();58 } else if (currentGlobalDisableDirective) {59 enabledRules.add(directive.ruleId);60 disabledRuleMap.delete(directive.ruleId);61 } else {62 disabledRuleMap.delete(directive.ruleId);63 }64 break;65 // no default66 }67 }68 if (disabledRuleMap.has(problem.ruleId)) {69 usedDisableDirectives.add(disabledRuleMap.get(problem.ruleId));70 } else if (currentGlobalDisableDirective && !enabledRules.has(problem.ruleId)) {71 usedDisableDirectives.add(currentGlobalDisableDirective);72 } else {73 problems.push(problem);74 }75 }76 const unusedDisableDirectives = options.directives77 .filter(directive => directive.type === "disable" && !usedDisableDirectives.has(directive))78 .map(directive => ({79 ruleId: null,80 message: directive.ruleId81 ? `Unused eslint-disable directive (no problems were reported from '${directive.ruleId}').`82 : "Unused eslint-disable directive (no problems were reported).",83 line: directive.unprocessedDirective.line,84 column: directive.unprocessedDirective.column,85 severity: options.reportUnusedDisableDirectives === "warn" ? 1 : 2,86 nodeType: null87 }));88 return { problems, unusedDisableDirectives };89}90/**91 * Given a list of directive comments (i.e. metadata about eslint-disable and eslint-enable comments) and a list92 * of reported problems, determines which problems should be reported.93 * @param {Object} options Information about directives and problems94 * @param {{95 * type: ("disable"|"enable"|"disable-line"|"disable-next-line"),96 * ruleId: (string|null),97 * line: number,98 * column: number99 * }} options.directives Directive comments found in the file, with one-based columns.100 * Two directive comments can only have the same location if they also have the same type (e.g. a single eslint-disable101 * comment for two different rules is represented as two directives).102 * @param {{ruleId: (string|null), line: number, column: number}[]} options.problems103 * A list of problems reported by rules, sorted by increasing location in the file, with one-based columns.104 * @param {"off" | "warn" | "error"} options.reportUnusedDisableDirectives If `"warn"` or `"error"`, adds additional problems for unused directives105 * @returns {{ruleId: (string|null), line: number, column: number}[]}106 * A list of reported problems that were not disabled by the directive comments.107 */108module.exports = ({ directives, problems, reportUnusedDisableDirectives = "off" }) => {109 const blockDirectives = directives110 .filter(directive => directive.type === "disable" || directive.type === "enable")111 .map(directive => Object.assign({}, directive, { unprocessedDirective: directive }))112 .sort(compareLocations);113 const lineDirectives = lodash.flatMap(directives, directive => {114 switch (directive.type) {115 case "disable":116 case "enable":117 return [];118 case "disable-line":119 return [120 { type: "disable", line: directive.line, column: 1, ruleId: directive.ruleId, unprocessedDirective: directive },121 { type: "enable", line: directive.line + 1, column: 0, ruleId: directive.ruleId, unprocessedDirective: directive }122 ];123 case "disable-next-line":124 return [125 { type: "disable", line: directive.line + 1, column: 1, ruleId: directive.ruleId, unprocessedDirective: directive },126 { type: "enable", line: directive.line + 2, column: 0, ruleId: directive.ruleId, unprocessedDirective: directive }127 ];128 default:129 throw new TypeError(`Unrecognized directive type '${directive.type}'`);130 }131 }).sort(compareLocations);132 const blockDirectivesResult = applyDirectives({133 problems,134 directives: blockDirectives,135 reportUnusedDisableDirectives136 });137 const lineDirectivesResult = applyDirectives({138 problems: blockDirectivesResult.problems,139 directives: lineDirectives,140 reportUnusedDisableDirectives141 });142 return reportUnusedDisableDirectives !== "off"143 ? lineDirectivesResult.problems144 .concat(blockDirectivesResult.unusedDisableDirectives)145 .concat(lineDirectivesResult.unusedDisableDirectives)146 .sort(compareLocations)147 : lineDirectivesResult.problems;...
use-directives.spec.js
Source:use-directives.spec.js
1// Copyright (c) 2016-2019 Electric Imp2// This file is licensed under the MIT License3// http://opensource.org/licenses/MIT4'use strict';5require('jasmine-expect');6const fs = require('fs');7const path = require('path');8const init = require('./init')('main');9const eol = require('eol');10const directivesUseFile = path.join(process.cwd(), 'use_directives.json');11const directivesSaveFile = path.join(process.cwd(), 'save_directives.json');12describe('Machine', () => {13 let machine;14 beforeEach(() => {15 machine = init.createMachine();16 });17 it('Create and read directives JSON file', () => {18 const directives = {19 IntType: 34,20 FloatType: 34.456,21 ExponentType1: 3E4,22 ExponentType2: 3e-2,23 StringType1: "str1",24 StringType2: "\"str2\"",25 BoolTypeTrue: true,26 BoolTypeFalse: false,27 NullType: null28 };29 const directivesSource = "@{IntType} @{FloatType} @{ExponentType1} @{ExponentType2} @{StringType1} @{StringType2} @{BoolTypeTrue} @{BoolTypeFalse} @{NullType}";30 const expectedOutput = `34 34.456 30000 0.03 str1 "str2" true false null`;31 // ensure that test JSON file does not exist32 if (fs.existsSync(directivesSaveFile)) {33 fs.unlinkSync(directivesSaveFile);34 }35 // create directives file36 machine.directivesSaveFile = directivesSaveFile;37 expect(eol.lf(machine.execute(directivesSource, directives))).toBe(expectedOutput);38 // check that JSON file was created39 if (!fs.existsSync(directivesSaveFile)) {40 fail(`The ${directivesSaveFile} file does not exist.`);41 }42 // check that we are able to read variables definitions from JSON file43 machine.directivesUseFile = directivesSaveFile;44 expect(eol.lf(machine.execute(directivesSource))).toBe(expectedOutput);45 // unlink directives file to avoid conflicts with unit-tests below46 fs.unlinkSync(directivesSaveFile);47 });48 it('Check that directives JSON file content is able to be merged with additional variable definitions', () => {49 const directives = {50 Int0: 990,51 Int1: 991,52 };53 const directivesSource = "@{Int0} @{Int1}";54 const expectedOutput = `990 991`;55 // ensure that test directives JSON file does not exist56 if (fs.existsSync(directivesSaveFile)) {57 fs.unlinkSync(directivesSaveFile);58 }59 // create directives file60 machine.directivesSaveFile = directivesSaveFile;61 expect(eol.lf(machine.execute(directivesSource, directives))).toBe(expectedOutput);62 // check that JSON file was created63 if (!fs.existsSync(directivesSaveFile)) {64 fail(`The ${directivesSaveFile} file does not exist.`);65 }66 // check that we are able to read variables definitions from JSON file67 machine.directivesUseFile = directivesSaveFile;68 expect(eol.lf(machine.execute(directivesSource + " @{Int2}", {Int2: 992}))).toBe(expectedOutput + " 992");69 // unlink directives file to avoid conflicts with unit-tests below70 fs.unlinkSync(directivesSaveFile);71 });72 it('Check ---save-directives/--use-directives options combination', () => {73 const directives = {74 Int0: 550,75 Int1: 551,76 Int2: 552,77 };78 const directivesSource = "@{Int0} @{Int1} @{Int2}";79 const expectedOutput = `550 551 552`;80 // ensure that test JSON file does not exist81 if (fs.existsSync(directivesSaveFile)) {82 fs.unlinkSync(directivesSaveFile);83 }84 // create directives file85 machine.directivesSaveFile = directivesUseFile;86 expect(eol.lf(machine.execute(directivesSource, directives))).toBe(expectedOutput);87 // check that directives JSON file was created88 if (!fs.existsSync(directivesUseFile)) {89 fail(`The ${directivesUseFile} file does not exist.`);90 }91 machine.directivesUseFile = directivesUseFile;92 machine.directivesSaveFile = directivesSaveFile;93 eol.lf(machine.execute(directivesSource, directives));94 // check that directives JSON file was created95 if (!fs.existsSync(directivesSaveFile)) {96 fail(`The ${directivesSaveFile} file does not exist.`);97 }98 // check that files are identical99 expect(fs.readFileSync(directivesUseFile)).toEqual(fs.readFileSync(directivesSaveFile));100 // unlink directives file to avoid conflicts with unit-tests below101 fs.unlinkSync(directivesSaveFile);102 fs.unlinkSync(directivesUseFile);103 });104 it('Check case when directives JSON file appear to be corrupted', () => {105 const directives = {106 Int0: 550,107 Int1: 551,108 Int2: 552,109 };110 const directivesSource = "@{Int0} @{Int1} @{Int2}";111 const expectedOutput = `550 551 552`;112 // ensure that test JSON file does not exist113 if (fs.existsSync(directivesSaveFile)) {114 fs.unlinkSync(directivesSaveFile);115 }116 // create directives file117 machine.directivesSaveFile = directivesSaveFile;118 expect(eol.lf(machine.execute(directivesSource, directives))).toBe(expectedOutput);119 // check that directives JSON file was created120 if (!fs.existsSync(directivesSaveFile)) {121 fail(`The ${directivesSaveFile} file does not exist.`);122 }123 // corrupt the file124 fs.appendFileSync(directivesSaveFile, ']');125 const fileCorruptedMessage = `The directives JSON file '${directivesSaveFile}' cannot be used: Unexpected token ] in JSON at position 47`;126 // check exception error message127 try {128 machine.directivesSaveFile = undefined;129 machine.directivesUseFile = directivesSaveFile;130 eol.lf(machine.execute(directivesSource, directives));131 } catch (e) {132 expect(e.message).toEqual(fileCorruptedMessage);133 }134 // unlink directives file to avoid conflicts with unit-tests below135 fs.unlinkSync(directivesSaveFile);136 });...
directives.ts
Source:directives.ts
1/**2 * @license3 * Copyright Google Inc. All Rights Reserved.4 *5 * Use of this source code is governed by an MIT-style license that can be6 * found in the LICENSE file at https://angular.io/license7 */8import {NgModule, Type} from '@angular/core';9import {CheckboxControlValueAccessor} from './directives/checkbox_value_accessor';10import {DefaultValueAccessor} from './directives/default_value_accessor';11import {NgControlStatus, NgControlStatusGroup} from './directives/ng_control_status';12import {NgForm} from './directives/ng_form';13import {NgModel} from './directives/ng_model';14import {NgModelGroup} from './directives/ng_model_group';15import {NumberValueAccessor} from './directives/number_value_accessor';16import {RadioControlValueAccessor} from './directives/radio_control_value_accessor';17import {FormControlDirective} from './directives/reactive_directives/form_control_directive';18import {FormControlName} from './directives/reactive_directives/form_control_name';19import {FormGroupDirective} from './directives/reactive_directives/form_group_directive';20import {FormArrayName, FormGroupName} from './directives/reactive_directives/form_group_name';21import {NgSelectOption, SelectControlValueAccessor} from './directives/select_control_value_accessor';22import {NgSelectMultipleOption, SelectMultipleControlValueAccessor} from './directives/select_multiple_control_value_accessor';23import {MaxLengthValidator, MinLengthValidator, PatternValidator, RequiredValidator} from './directives/validators';24export {CheckboxControlValueAccessor} from './directives/checkbox_value_accessor';25export {ControlValueAccessor} from './directives/control_value_accessor';26export {DefaultValueAccessor} from './directives/default_value_accessor';27export {NgControl} from './directives/ng_control';28export {NgControlStatus, NgControlStatusGroup} from './directives/ng_control_status';29export {NgForm} from './directives/ng_form';30export {NgModel} from './directives/ng_model';31export {NgModelGroup} from './directives/ng_model_group';32export {NumberValueAccessor} from './directives/number_value_accessor';33export {RadioControlValueAccessor} from './directives/radio_control_value_accessor';34export {FormControlDirective} from './directives/reactive_directives/form_control_directive';35export {FormControlName} from './directives/reactive_directives/form_control_name';36export {FormGroupDirective} from './directives/reactive_directives/form_group_directive';37export {FormArrayName, FormGroupName} from './directives/reactive_directives/form_group_name';38export {NgSelectOption, SelectControlValueAccessor} from './directives/select_control_value_accessor';39export {NgSelectMultipleOption, SelectMultipleControlValueAccessor} from './directives/select_multiple_control_value_accessor';40export {MaxLengthValidator, MinLengthValidator, PatternValidator, RequiredValidator} from './directives/validators';41export const SHARED_FORM_DIRECTIVES: Type<any>[] = [42 NgSelectOption, NgSelectMultipleOption, DefaultValueAccessor, NumberValueAccessor,43 CheckboxControlValueAccessor, SelectControlValueAccessor, SelectMultipleControlValueAccessor,44 RadioControlValueAccessor, NgControlStatus, NgControlStatusGroup, RequiredValidator,45 MinLengthValidator, MaxLengthValidator, PatternValidator46];47export const TEMPLATE_DRIVEN_DIRECTIVES: Type<any>[] = [NgModel, NgModelGroup, NgForm];48export const REACTIVE_DRIVEN_DIRECTIVES: Type<any>[] =49 [FormControlDirective, FormGroupDirective, FormControlName, FormGroupName, FormArrayName];50/**51 * A list of all the form directives.52 *53 * @stable54 */55export const FORM_DIRECTIVES: Type<any>[][] = [TEMPLATE_DRIVEN_DIRECTIVES, SHARED_FORM_DIRECTIVES];56/**57 * @stable58 */59export const REACTIVE_FORM_DIRECTIVES: Type<any>[][] =60 [REACTIVE_DRIVEN_DIRECTIVES, SHARED_FORM_DIRECTIVES];61/**62 * Internal module used for sharing directives between FormsModule and ReactiveFormsModule63 */64@NgModule({declarations: SHARED_FORM_DIRECTIVES, exports: SHARED_FORM_DIRECTIVES})65export class InternalFormsSharedModule {...
Using AI Code Generation
1import { MockBuilder, MockRender } from 'ng-mocks';2import { AppModule } from './app.module';3import { AppComponent } from './app.component';4describe('AppComponent', () => {5 beforeEach(() => MockBuilder(AppComponent, AppModule));6 it('should create the app', () => {7 const fixture = MockRender(AppComponent);8 const app = fixture.debugElement.componentInstance;9 expect(app).toBeTruthy();10 });11});12import { NgModule } from '@angular/core';13import { BrowserModule } from '@angular/platform-browser';14import { AppComponent } from './app.component';15@NgModule({16 imports: [BrowserModule],17})18export class AppModule {}19import { Component } from '@angular/core';20@Component({21})22export class AppComponent {}23import { MockBuilder, MockRender } from 'ng-mocks';24import { AppComponent } from './app.component';25import { AppModule } from './app.module';26describe('AppComponent', () => {27 beforeEach(() => MockBuilder(AppComponent, AppModule));28 it('should create the app', () => {29 const fixture = MockRender(AppComponent);30 const app = fixture.debugElement.componentInstance;31 expect(app).toBeTruthy();32 });33});34h1 {35 color: red;36}37import { MockBuilder, MockRender } from 'ng-mocks';38import { AppComponent } from './app.component';39import { AppModule } from './app.module';40describe('AppComponent', () => {41 beforeEach(() => MockBuilder(AppComponent, AppModule));42 it('should create the app', () => {43 const fixture = MockRender(AppComponent);44 const app = fixture.debugElement.componentInstance;45 expect(app).toBeTruthy();46 });47});48h1 {49 color: red;50}51import { MockBuilder, MockRender } from 'ng-mocks';52import { AppComponent } from './app.component';53import { AppModule } from './app.module';54describe('AppComponent', () => {
Using AI Code Generation
1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2describe('MyComponent', () => {3 beforeEach(() => MockBuilder(MyComponent));4 it('renders', () => {5 const fixture = MockRender(MyComponent);6 const element = ngMocks.find('h1');7 expect(element).toBeDefined();8 });9});
Using AI Code Generation
1describe('test', function() {2 var element;3 var scope;4 var $compile;5 beforeEach(module('myApp'));6 beforeEach(inject(function(_$compile_, $rootScope) {7 $compile = _$compile_;8 scope = $rootScope.$new();9 element = $compile('<div my-directive></div>')(scope);10 }));11 it('should work', function() {12 });13});14angular.module('myApp').directive('myDirective', function() {15 return {16 link: function(scope, element, attrs) {17 }18 };19});20describe('test', function() {21 var element;22 var scope;23 var $compile;24 beforeEach(module('myApp'));25 beforeEach(inject(function(_$compile_, $rootScope) {26 $compile = _$compile_;27 scope = $rootScope.$new();28 element = $compile('<div my-directive></div>')(scope);29 }));30 it('should work', function() {31 });32});33angular.module('myApp').directive('myDirective', function() {34 return {35 compile: function(element, attrs) {36 return {37 pre: function(scope, element, attrs) {38 }39 };40 }41 };42});
Using AI Code Generation
1import { mockModule } from 'ng-mocks';2import { MyModule } from './my-module';3describe('MyModule', () => {4 it('should be created', () => {5 const module = mockModule(MyModule, {6 imports: [ ... ],7 });8 expect(module).toBeTruthy();9 });10});11import { NgModule } from '@angular/core';12@NgModule({13 imports: [ ... ],14})15export class MyModule {}
Using AI Code Generation
1describe('directive', function() {2 var element;3 beforeEach(inject(function($compile, $rootScope) {4 element = $compile('<div directive></div>')($rootScope);5 }));6 it('should be compiled', function() {7 expect(element.html()).not.toEqual(null);8 });9 it('should have isolate scope object with instanciate members', function() {10 expect(element.isolateScope().vm).toEqual(jasmine.any(Object));11 });12 it('should have isolate scope object with instanciate members', function() {13 expect(element.isolateScope().vm).toEqual(jasmine.any(Object));14 });15});16 .module('app')17 .directive('directive', directive);18function directive() {19 var directive = {20 scope: {}21 };22 return directive;23 function link(scope, element, attrs) {}24}25function Controller() {}26module.exports = function(config) {27 config.set({
Using AI Code Generation
1describe("test", function() {2 beforeEach(function() {3 module('myApp');4 module(function($provide) {5 $provide.decorator('$log', function($delegate) {6 $delegate.log = function() {7 console.log(arguments);8 }9 return $delegate;10 });11 });12 });13 it('should log', inject(function($log) {14 $log.log('test');15 }));16});
Using AI Code Generation
1describe('Test for directives', function() {2 beforeEach(angular.mock.module('myApp'));3 it('should have a directive', function() {4 var element = '<div my-directive></div>';5 var directive = angular.mock.inject(function($compile, $rootScope) {6 var scope = $rootScope.$new();7 var element = $compile(element)(scope);8 scope.$digest();9 return element;10 });11 expect(directive).toBeDefined();12 });13});14angular.module('myApp', [])15.directive('myDirective', function() {16 var directive = {};17 directive.restrict = 'A';18 directive.template = '<div>My Directive</div>';19 return directive;20});21describe('Test for services', function() {22 beforeEach(angular.mock.module('myApp'));23 it('should have a service', function() {24 var service = angular.mock.inject(function(myService) {25 return myService;26 });27 expect(service).toBeDefined();28 });29});30angular.module('myApp', [])31.service('myService', function() {32 var service = {};33 service.name = 'My Service';34 return service;35});36describe('Test for filters', function() {37 beforeEach(angular.mock.module('myApp'));38 it('should have a filter', function() {39 var filter = angular.mock.inject(function(myFilter) {40 return myFilter;41 });42 expect(filter).toBeDefined();43 });44});45angular.module('myApp', [])46.filter('myFilter', function() {47 return function(input) {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!