Best JavaScript code snippet using ng-mocks
ViewProviderSpec.js
Source:ViewProviderSpec.js
1/*****************************************************************************2 * Open MCT, Copyright (c) 2014-2018, United States Government3 * as represented by the Administrator of the National Aeronautics and Space4 * Administration. All rights reserved.5 *6 * Open MCT is licensed under the Apache License, Version 2.0 (the7 * "License"); you may not use this file except in compliance with the License.8 * You may obtain a copy of the License at9 * http://www.apache.org/licenses/LICENSE-2.0.10 *11 * Unless required by applicable law or agreed to in writing, software12 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT13 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the14 * License for the specific language governing permissions and limitations15 * under the License.16 *17 * Open MCT includes source code licensed under additional open source18 * licenses. See the Open Source Licenses file (LICENSES.md) included with19 * this source code distribution or the Licensing information page available20 * at runtime from the About dialog for additional information.21 *****************************************************************************/22/**23 * ViewProviderSpec. Created by vwoeltje on 11/6/14.24 */25define(26 ["../../src/views/ViewProvider"],27 function (ViewProvider) {28 describe("The view provider", function () {29 var viewA = {30 key: "a"31 },32 viewB = {33 key: "b",34 needs: ["someCapability"]35 },36 viewC = {37 key: "c",38 needs: ["someCapability"],39 delegation: true40 },41 capabilities = {},42 delegates = {},43 delegation,44 mockDomainObject = {},45 mockLog,46 provider;47 beforeEach(function () {48 // Simulate the expected API49 mockDomainObject.hasCapability = function (c) {50 return capabilities[c] !== undefined;51 };52 mockDomainObject.getCapability = function (c) {53 return capabilities[c];54 };55 mockDomainObject.useCapability = function (c, v) {56 return capabilities[c] && capabilities[c].invoke(v);57 };58 mockLog = jasmine.createSpyObj("$log", ["warn", "info", "debug"]);59 capabilities = {};60 delegates = {};61 delegation = {62 doesDelegateCapability: function (c) {63 return delegates[c] !== undefined;64 }65 };66 provider = new ViewProvider([viewA, viewB, viewC], mockLog);67 });68 it("reports views provided as extensions", function () {69 capabilities.someCapability = true;70 expect(provider.getViews(mockDomainObject))71 .toEqual([viewA, viewB, viewC]);72 });73 it("filters views by needed capabilities", function () {74 //capabilities.someCapability = true;75 expect(provider.getViews(mockDomainObject))76 .toEqual([viewA]);77 });78 it("allows delegation of needed capabilities when specified", function () {79 //capabilities.someCapability = true;80 capabilities.delegation = delegation;81 delegates.someCapability = true;82 expect(provider.getViews(mockDomainObject))83 .toEqual([viewA, viewC]);84 });85 it("warns if keys are omitted from views", function () {86 // Verify that initial construction issued no warning87 expect(mockLog.warn).not.toHaveBeenCalled();88 // Recreate with no keys; that view should be filtered out89 expect(90 new ViewProvider(91 [viewA, { some: "bad view" }],92 mockLog93 ).getViews(mockDomainObject)94 ).toEqual([viewA]);95 // We should have also received a warning, to support debugging96 expect(mockLog.warn).toHaveBeenCalledWith(jasmine.any(String));97 });98 it("restricts typed views to matching types", function () {99 var testType = "testType",100 testView = { key: "x", type: testType },101 viewProvider = new ViewProvider([testView], mockLog);102 // Include a "type" capability103 capabilities.type = jasmine.createSpyObj(104 "type",105 ["instanceOf", "invoke", "getDefinition"]106 );107 capabilities.type.invoke.and.returnValue(capabilities.type);108 // Should be included when types match109 capabilities.type.instanceOf.and.returnValue(true);110 expect(viewProvider.getViews(mockDomainObject))111 .toEqual([testView]);112 expect(capabilities.type.instanceOf)113 .toHaveBeenCalledWith(testType);114 // ...but not when they don't115 capabilities.type.instanceOf.and.returnValue(false);116 expect(viewProvider.getViews(mockDomainObject))117 .toEqual([]);118 });119 it("enforces view restrictions from types", function () {120 var testView = { key: "x" },121 viewProvider = new ViewProvider([testView], mockLog);122 // Include a "type" capability123 capabilities.type = jasmine.createSpyObj(124 "type",125 ["instanceOf", "invoke", "getDefinition"]126 );127 capabilities.type.invoke.and.returnValue(capabilities.type);128 // Should be included when view keys match129 capabilities.type.getDefinition130 .and.returnValue({ views: [testView.key]});131 expect(viewProvider.getViews(mockDomainObject))132 .toEqual([testView]);133 // ...but not when they don't134 capabilities.type.getDefinition135 .and.returnValue({ views: ["somethingElse"]});136 expect(viewProvider.getViews(mockDomainObject))137 .toEqual([]);138 });139 });140 }...
main.js
Source:main.js
1import headerTemplate from './components/header/template.js'2import productsTemplate from './components/products/template.js'3import modalTemplate from './components/modal/template.js'4function GlobalInformation() {5 let showShopping = ko.observable('isHidden')6 let cart = ko.observableArray([])7 return {8 showShopping,9 cart,10 }11}12const viewProvider = new GlobalInformation()13function Products() {14 this.products = ko.observableArray([15 {16 id: 1,17 name: 'Suco integral',18 description: 'Aurora 1,5L',19 price: 14.22,20 image: './assets/products/suco_uva.png',21 },22 {23 id: 2,24 name: 'Achocolatado',25 description: 'Toddy 400 g',26 price: 4.5,27 image: './assets/products/achocolatado.png',28 },29 {30 id: 3,31 name: 'Leite de Coco',32 description: 'Menina 200 ml',33 price: 3.5,34 image: './assets/products/leite_coco.png',35 },36 {37 id: 4,38 name: 'Amaciante',39 description: 'Monbjoux 2 l',40 price: 22.4,41 image: './assets/products/amaciante.png',42 },43 {44 id: 5,45 name: 'Agua sanitaria',46 description: 'Qboa 200ml',47 price: 11.5,48 image: './assets/products/q-boa-mini.png',49 },50 {51 id: 6,52 name: 'Agua sanitaria big',53 description: 'Qboa 1l',54 price: 32.1,55 image: './assets/products/qboa.png',56 },57 ])58}59function Cart() {60 this.cart = viewProvider.cart()61 this.handleAddProductInCart = (data) => {62 const filter = viewProvider.cart().filter((item) => item.id !== data.id)63 const itemInCart = viewProvider.cart().find((item) => item.id === data.id)64 if (itemInCart) {65 return viewProvider.cart([66 ...filter,67 { ...data, qty: itemInCart.qty + 1 },68 ])69 }70 return viewProvider.cart([71 ...viewProvider.cart(),72 { ...data, qty: 1, selected: true },73 ])74 }75 this.cartQty = ko.computed(() => {76 const value = viewProvider.cart().reduce(77 (acc, curren) => {78 return { qty: acc.qty + curren.qty }79 },80 { qty: 0 }81 )82 return `${value.qty} items`83 })84 this.cartTotalValue = ko.computed(() => {85 const { price } = viewProvider.cart().reduce(86 (acc, curren) => {87 return { price: acc.price + curren.price * curren.qty }88 },89 { price: 0 }90 )91 return `R$ ${price.toFixed(2)}`92 })93}94ko.components.register('header-component', {95 template: headerTemplate,96 viewModel: function (params) {97 this.user = {98 firstName: ko.observable('Angela Pires'),99 avatar: ko.observable('./assets/avatar.png'),100 }101 this.handleShowShopping = () => {102 if (params.cart().length > 0) {103 viewProvider.showShopping('isShow')104 }105 }106 this.isAvalibleCartItems = ko.computed(() => {107 return params.cart().length > 0 && 'avalible'108 })109 },110})111ko.components.register('products', {112 template: productsTemplate,113 viewModel: function (params) {114 const { products } = new Products()115 const { handleAddProductInCart, removeItemFromCart } = new Cart()116 this.handleAddProductInCart = handleAddProductInCart117 this.removeItemFromCart = removeItemFromCart118 this.products = products()119 },120})121ko.components.register('modal', {122 template: modalTemplate,123 viewModel: function () {124 this.cart = ko.computed(() => {125 return viewProvider.cart()126 })127 this.handleHideShopping = () => {128 viewProvider.showShopping('isHidden')129 }130 this.removeItemFromCart = (value, event) => {131 event.stopPropagation()132 const confirm = window.confirm(133 'Tem certeza que deseja remover este item?'134 )135 if (confirm) {136 return viewProvider.cart(137 viewProvider.cart().filter((item) => item.id !== value.id)138 )139 }140 return141 }142 this.showShopping = ko.computed(() => viewProvider.showShopping())143 this.cartTotalValue = ko.computed(() => {144 const { price } = viewProvider.cart().reduce(145 (acc, curren) => {146 return { price: acc.price + curren.price * curren.qty }147 },148 { price: 0 }149 )150 return `R$ ${price.toFixed(2)}`151 })152 this.cartQty = ko.computed(() => {153 const value = viewProvider.cart().reduce(154 (acc, curren) => {155 return { qty: acc.qty + curren.qty }156 },157 { qty: 0 }158 )159 return `${value.qty} items`160 })161 },162})...
test.spec.ts
Source:test.spec.ts
1import { Component, Injectable, Input } from '@angular/core';2import {3 MockBuilder,4 MockInstance,5 MockProvider,6 MockRender,7 ngMocks,8} from 'ng-mocks';9@Injectable()10export class ProviderService {11 public description = 'real provider';12}13@Injectable()14export class ViewProviderService {15 public description = 'real viewProvider';16}17@Component({18 providers: [ProviderService],19 selector: 'hello',20 template: `21 <h1 class="name">{{ name }}</h1>22 <div class="provider">{{ provider.description }}</div>23 <div class="viewProvider">{{ viewProvider.description }}</div>24 `,25 viewProviders: [ViewProviderService],26})27export class HelloComponent {28 @Input() public readonly name: string | null = null;29 public constructor(30 public readonly provider: ProviderService,31 public readonly viewProvider: ViewProviderService,32 ) {}33}34// @see https://github.com/help-me-mom/ng-mocks/issues/150735// Difference between MockBuilder.provide and MockBuilder.mock36// Only MockBuilder.mock replaces providers on the component / directive level.37// MockBuilder.provide simply adds a service to global scope.38describe('issue-1507', () => {39 MockInstance.scope();40 describe('default', () => {41 beforeEach(() => MockBuilder(HelloComponent));42 it('keeps providers and viewProviders as they are', () => {43 MockRender(HelloComponent, { name: 'Test1' });44 const name = ngMocks.formatText(ngMocks.find('.name'));45 expect(name).toEqual('Test1');46 const provider = ngMocks.formatText(ngMocks.find('.provider'));47 expect(provider).toEqual('real provider');48 const viewProvider = ngMocks.formatText(49 ngMocks.find('.viewProvider'),50 );51 expect(viewProvider).toEqual('real viewProvider');52 });53 });54 describe('.keep', () => {55 beforeEach(() =>56 MockBuilder(HelloComponent)57 .keep(ProviderService)58 .keep(ViewProviderService),59 );60 it('keeps providers and viewProviders as they are', () => {61 MockRender(HelloComponent, { name: 'Test2' });62 const name = ngMocks.formatText(ngMocks.find('.name'));63 expect(name).toEqual('Test2');64 const provider = ngMocks.formatText(ngMocks.find('.provider'));65 expect(provider).toEqual('real provider');66 const viewProvider = ngMocks.formatText(67 ngMocks.find('.viewProvider'),68 );69 expect(viewProvider).toEqual('real viewProvider');70 });71 });72 describe('.provide', () => {73 beforeEach(() =>74 MockBuilder(HelloComponent)75 .provide(76 MockProvider(ProviderService, {77 description: 'provided provider',78 }),79 )80 .provide(81 MockProvider(ViewProviderService, {82 description: 'provided viewProvider',83 }),84 ),85 );86 it('provides mocks on the root level', () => {87 MockRender(HelloComponent, { name: 'Test3' });88 const name = ngMocks.formatText(ngMocks.find('.name'));89 expect(name).toEqual('Test3');90 const provider = ngMocks.formatText(ngMocks.find('.provider'));91 expect(provider).toEqual('real provider');92 expect(93 ngMocks.findInstance(ProviderService).description,94 ).toEqual('provided provider');95 const viewProvider = ngMocks.formatText(96 ngMocks.find('.viewProvider'),97 );98 expect(viewProvider).toEqual('real viewProvider');99 expect(100 ngMocks.findInstance(ViewProviderService).description,101 ).toEqual('provided viewProvider');102 });103 });104 describe('.mock', () => {105 beforeEach(() =>106 MockBuilder(HelloComponent)107 .mock(ProviderService, {108 description: 'mock provider',109 })110 .mock(ViewProviderService, {111 description: 'mock viewProvider',112 }),113 );114 it('mocks services on the component level', () => {115 MockRender(HelloComponent, { name: 'Test4' });116 const name = ngMocks.formatText(ngMocks.find('.name'));117 expect(name).toEqual('Test4');118 const provider = ngMocks.formatText(ngMocks.find('.provider'));119 expect(provider).toEqual('mock provider');120 const viewProvider = ngMocks.formatText(121 ngMocks.find('.viewProvider'),122 );123 expect(viewProvider).toEqual('mock viewProvider');124 });125 });...
Using AI Code Generation
1import { viewProvider } from 'ng-mocks';2describe('TestComponent', () => {3 let component: TestComponent;4 let fixture: ComponentFixture<TestComponent>;5 beforeEach(async(() => {6 TestBed.configureTestingModule({7 providers: [viewProvider(TestService)]8 })9 .compileComponents();10 }));11 beforeEach(() => {12 fixture = TestBed.createComponent(TestComponent);13 component = fixture.componentInstance;14 fixture.detectChanges();15 });16 it('should create', () => {17 expect(component).toBeTruthy();18 });19});20import { Injectable } from '@angular/core';21@Injectable()22export class TestService {23 constructor() { }24 testMethod() {25 return 'test';26 }27}28import { Component, OnInit } from '@angular/core';29import { TestService } from 'test.service';30@Component({31})32export class TestComponent implements OnInit {33 constructor(private testService: TestService) { }34 ngOnInit(): void {35 console.log(this.testService.testMethod());36 }37}38import { ComponentFixture, TestBed, async } from '@angular/core/testing';39import { TestComponent } from 'test.component';40describe('TestComponent', () => {41 let component: TestComponent;42 let fixture: ComponentFixture<TestComponent>;43 beforeEach(async(() => {44 TestBed.configureTestingModule({45 })46 .compileComponents();47 }));48 beforeEach(() => {49 fixture = TestBed.createComponent(TestComponent);50 component = fixture.componentInstance;51 fixture.detectChanges();52 });53 it('should create', () => {54 expect(component).toBeTruthy();55 });56});
Using AI Code Generation
1import { TestBed, async } from '@angular/core/testing';2import { AppComponent } from './app.component';3import { MockBuilder, MockRender } from 'ng-mocks';4import { AppModule } from './app.module';5describe('AppComponent', () => {6 beforeEach(async(() => MockBuilder(AppComponent, AppModule)));7 it('should create the app', async(() => {8 const fixture = MockRender(AppComponent);9 const app = fixture.point.componentInstance;10 expect(app).toBeTruthy();11 }));12 it(`should have as title 'app'`, async(() => {13 const fixture = MockRender(AppComponent);14 const app = fixture.point.componentInstance;15 expect(app.title).toEqual('app');16 }));17 it('should render title in a h1 tag', async(() => {18 const fixture = MockRender(AppComponent);19 fixture.detectChanges();20 const compiled = fixture.point.nativeElement;21 expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');22 }));23});24import { Component, OnInit } from '@angular/core';25import { HttpClient } from '@angular/common/http';26import { Observable } from 'rxjs/Observable';27import { map } from 'rxjs/operators';28import { of } from 'rxjs/observable/of';29@Component({30 {31 useValue: {32 get: () => of({ some: 'value' }),33 },34 },35})36export class AppComponent implements OnInit {37 title = 'app';38 data$: Observable<any>;39 constructor(private http: HttpClient) {}40 ngOnInit() {41 this.data$ = this.http.get('/some-url').pipe(map(res => res));42 }43}44import { Component, OnInit } from '@angular/core';45import { HttpClient } from '@angular/common/http';46import { Observable } from 'rxjs/Observable';47import { map } from 'rxjs/operators';48import { of } from 'rxjs/observable/of';49@Component({
Using AI Code Generation
1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2import { MyComponent } from './my.component';3beforeEach(() => MockBuilder(MyComponent));4it('renders', () => {5 ngMocks.viewProvider(MyComponent, {6 });7 const fixture = MockRender(MyComponent);8 expect(fixture.point.nativeElement).toHaveText('mocked');9});10In this article, we learned how to use ng-mocks to mock the view of a component. We also learned how to use ng-mocks to mock the view of a module. We also learned how to use ng-mocks to mock the view of a component that is imported into a module. We also learned how to use ng-mocks to mock the view of a component that is imported into another component. We also learned how to use ng-mocks to mock the view of a component that is imported into a module that is imported into another module. We also learned how to use ng-mocks to mock the view of a component that is imported into a module that is imported into another module that is imported into another module. We also learned how to use ng-mocks to mock the view of a component that is imported into a module that is imported into another module that is imported into another module that is imported into another module. We also learned how to use ng-mocks to mock the view of a component that is imported into a module that is imported into another module that is imported into another module that is imported into another module that is imported into another module. We also learned how to use ng-mocks to mock the view of a component that is imported into a module that is imported into another module that is imported into another module that is imported into another module that is imported into another module that is imported into another module. We also learned how to use ng-mocks to mock the view of a component that is imported into a module that is imported into another module that is imported into another module that is imported into another module
Using AI Code Generation
1ngMocks.viewProvider({2 useValue: mock(SomeService),3});4ngMocks.viewProvider(SomeService, mock(SomeService));5ngMocks.viewProvider(SomeService, {6 useValue: mock(SomeService),7});8ngMocks.viewProvider(SomeService, mock(SomeService));9ngMocks.viewProvider(SomeService, {10 useValue: mock(SomeService),11});12ngMocks.viewProvider(SomeService, mock(SomeService));13ngMocks.viewProvider(SomeService, {14 useValue: mock(SomeService),15});16ngMocks.viewProvider(SomeService, mock(SomeService));17ngMocks.viewProvider(SomeService, {18 useValue: mock(SomeService),19});20ngMocks.viewProvider(SomeService, mock(SomeService));21ngMocks.viewProvider(SomeService, {22 useValue: mock(SomeService),23});24ngMocks.viewProvider(SomeService, mock(SomeService));25ngMocks.viewProvider(SomeService, {26 useValue: mock(SomeService),27});28ngMocks.viewProvider(SomeService, mock(SomeService));29ngMocks.viewProvider(SomeService, {30 useValue: mock(SomeService),31});32ngMocks.viewProvider(SomeService, mock(SomeService));
Using AI Code Generation
1import { mockProvider } from 'ng-mocks';2import { MyService } from './my-service';3describe('Test', () => {4 it('should work', () => {5 const viewProvider = mockProvider(MyService);6 const mock = viewProvider.getMock();7 mock.spyOn('name').and.returnValue('Mocked name');8 const service = viewProvider.injector.get(MyService);9 expect(service.name()).toBe('Mocked name');10 });11});12import { Injectable } from '@angular/core';13@Injectable()14export class MyService {15 public name(): string {16 return 'My name';17 }18}
Using AI Code Generation
1import { viewProvider } from 'ng-mocks';2import { MyComponent } from './my.component';3const fixture = viewProvider(MyComponent, {4 { provide: Service1, useValue: mockService1 },5 { provide: Service2, useValue: mockService2 },6});7const component = fixture.componentInstance;8const element = fixture.nativeElement;9const debugElement = fixture.debugElement;10const html = element.innerHTML;11const text = element.textContent;12const styles = element.style;13const classList = element.classList;14const attributes = element.attributes;15const children = element.children;16const firstChild = element.firstChild;17const lastChild = element.lastChild;18const nextSibling = element.nextSibling;19const previousSibling = element.previousSibling;20const parent = element.parentElement;21const childNodes = element.childNodes;22const firstChildNode = element.firstChildNode;23const lastChildNode = element.lastChildNode;24const childElementNodes = element.childElementNodes;25const firstChildElementNode = element.firstChildElementNode;26const lastChildElementNode = element.lastChildElementNode;
Using AI Code Generation
1describe('viewProvider', () => {2 it('should render the template', () => {3 const fixture = MockRender(`4 `);5 expect(fixture.point.componentInstance).toBeDefined();6 });7});8describe('AppComponent', () => {9 it('should create the app', () => {10 const fixture = MockRender(`11 `);12 expect(fixture.point.componentInstance).toBeDefined();13 });14});15import { Component } from '@angular/core';16@Component({17})18export class AppComponent {19 title = 'angular-testing';20}21import { MockRender } from 'ng-mocks';22describe('AppComponent', () => {23 it('should create the app', () => {24 const fixture = MockRender(`25 `);26 expect(fixture.point.componentInstance).toBeDefined();27 });28});29import { Component } from '@angular/core';30@Component({31})32export class AppComponent {33 title = 'angular-testing';34}35import { MockRender } from 'ng-mocks';36describe('AppComponent', () => {37 it('should create the app', () => {38 const fixture = MockRender(`39 `);40 expect(fixture.point.componentInstance).toBeDefined();41 });42});43import { Component } from '@angular/core';44@Component({45})46export class AppComponent {47 title = 'angular-testing';48}49import { MockRender } from 'ng-mocks';50describe('AppComponent', () => {51 it('should create the app', () => {52 const fixture = MockRender(`
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!!