Best JavaScript code snippet using ng-mocks
add-spec.ts
Source:add-spec.ts
1import { IgniteUIForAngularTemplate } from "@igniteui/angular-templates";2import { App, GoogleAnalytics, PackageManager, ProjectConfig, TypeScriptFileUpdate, TypeScriptUtils, Util } from "@igniteui/cli-core";3import * as path from "path";4import * as ts from "typescript";5import { default as addCmd } from "../../packages/cli/lib/commands/add";6import { PromptSession } from "../../packages/cli/lib/PromptSession";7import { AngularTemplate } from "../../packages/cli/lib/templates/AngularTemplate";8import { resetSpy } from "../helpers/utils";9describe("Unit - Add command", () => {10 beforeEach(() => {11 spyOn(GoogleAnalytics, "post");12 });13 it("Should start prompt session with missing arg", async done => {14 spyOn(ProjectConfig, "hasLocalConfig").and.returnValue(true);15 spyOn(ProjectConfig, "getConfig").and.returnValue({ project: {16 framework: "angular",17 theme: "infragistics"}});18 const mockProjLib = {};19 addCmd.templateManager = jasmine.createSpyObj("TemplateManager", {20 getFrameworkById: {},21 getProjectLibrary: mockProjLib22 });23 const promptSession = PromptSession.prototype;24 spyOn(promptSession, "chooseActionLoop");25 await addCmd.execute({});26 expect(promptSession.chooseActionLoop).toHaveBeenCalledWith(mockProjLib);27 done();28 });29 it("Should validate and trim name", async done => {30 spyOn(ProjectConfig, "getConfig").and.returnValue({ project: {31 framework: "angular",32 theme: "infragistics"}});33 spyOn(Util, "error");34 spyOn(Util, "processTemplates").and.returnValue(Promise.resolve(false));35 spyOn(process, "cwd").and.returnValue("Mock directory");36 const mockTemplate = jasmine.createSpyObj("Template", ["generateConfig", "templatePath", "registerInProject"]);37 const mockConfig = { test: "test" };38 mockTemplate.generateConfig.and.returnValue(mockConfig);39 mockTemplate.templatePaths = ["test"];40 const mockDelimiters = { mockDelimiter: { start: "test", end: "test" }};41 mockTemplate.delimiters = mockDelimiters;42 const errorCombos = [43 { name: "name.ts", inError: "name.ts" }, // file extension test44 { name: "1 is not valid", inError: "1 is not valid" },45 { name: " 1 is not valid \t ", inError: "1 is not valid" },46 { name: "name!", inError: "name!" },47 { name: "bits~and*bobs()", inError: "bits~and*bobs()" }48 ];49 for (const item of errorCombos) {50 resetSpy(Util.error);51 await addCmd.addTemplate(item.name, mockTemplate);52 expect(Util.error).toHaveBeenCalledWith(`Name '${item.inError}' is not valid. `53 + "Name should start with a letter and can also contain numbers, dashes and spaces.", "red");54 }55 const validCombos = [56 { name: " valid name \t ", valid: "valid name" },57 { name: "th1s is valid", valid: "th1s is valid" },58 { name: "b1ts-and bobs ", valid: "b1ts-and bobs" },59 { name: "../editors", valid: "../editors" },60 { name: "template/editors", valid: "template/editors" },61 { name: "a name", valid: "a name" },62 { name: "a", valid: "a" } // single letter name test63 ];64 for (const item of validCombos) {65 await addCmd.addTemplate(item.name, mockTemplate);66 expect(mockTemplate.generateConfig).toHaveBeenCalledWith(item.valid, {});67 expect(Util.processTemplates).toHaveBeenCalledWith("test", "Mock directory", mockConfig, mockDelimiters);68 }69 done();70 });71 it("Should queue package dependencies and wait for install", async done => {72 spyOn(ProjectConfig, "getConfig").and.returnValue({ project: {73 framework: "angular",74 theme: "infragistics"}});75 spyOn(Util, "log");76 spyOn(PackageManager, "queuePackage");77 spyOn(Util, "processTemplates").and.returnValue(Promise.resolve(true));78 const mockTemplate = jasmine.createSpyObj("Template", ["generateConfig", "registerInProject"]);79 mockTemplate.templatePaths = ["test"];80 mockTemplate.packages = ["tslib" , "test-pack"];81 addCmd.templateManager = jasmine.createSpyObj("TemplateManager", ["updateProjectConfiguration"]);82 await addCmd.addTemplate("template with packages", mockTemplate);83 expect(mockTemplate.generateConfig).toHaveBeenCalled();84 expect(mockTemplate.registerInProject).toHaveBeenCalled();85 expect(Util.processTemplates).toHaveBeenCalledTimes(1);86 expect(addCmd.templateManager.updateProjectConfiguration).toHaveBeenCalled();87 expect(PackageManager.queuePackage).toHaveBeenCalledTimes(2);88 expect(PackageManager.queuePackage).toHaveBeenCalledWith("tslib");89 expect(PackageManager.queuePackage).toHaveBeenCalledWith("test-pack");90 spyOn(ProjectConfig, "hasLocalConfig").and.returnValue(true);91 addCmd.templateManager = jasmine.createSpyObj("TemplateManager", {92 getFrameworkById: {},93 getProjectLibrary: jasmine.createSpyObj("ProjectLibrary", {94 getTemplateById: {},95 hasTemplate: true96 })97 });98 spyOn(addCmd, "addTemplate");99 spyOn(PackageManager, "flushQueue").and.returnValue(Promise.resolve());100 spyOn(PackageManager, "ensureIgniteUISource");101 await addCmd.execute({name: "template with packages", template: "test-id"});102 expect(addCmd.addTemplate).toHaveBeenCalledWith("template with packages", {}, jasmine.any(Object));103 expect(PackageManager.flushQueue).toHaveBeenCalled();104 done();105 });106 it("Should properly accept module args when passed - IgniteUI for Angular", async done => {107 const mockProjectConfig = {project: {108 framework: "angular",109 theme: "infragistics"110 }};111 spyOn(TypeScriptUtils, "getFileSource").and.returnValue(112 ts.createSourceFile("test-file-name", ``, ts.ScriptTarget.Latest, true)113 );114 const routeSpy = spyOn(TypeScriptFileUpdate.prototype, "addRoute");115 const declarationSpy = spyOn(TypeScriptFileUpdate.prototype, "addDeclaration").and.callThrough();116 const ngMetaSpy = spyOn(TypeScriptFileUpdate.prototype, "addNgModuleMeta");117 const finalizeSpy = spyOn(TypeScriptFileUpdate.prototype, "finalize");118 const mockTemplate = new IgniteUIForAngularTemplate("test");119 mockTemplate.packages = [];120 mockTemplate.dependencies = [];121 const directoryPath = path.join("My/Example/Path");122 spyOn(process, "cwd").and.returnValue(directoryPath);123 spyOn(mockTemplate, "generateConfig");124 spyOn(Util, "processTemplates").and.returnValue(Promise.resolve(true));125 spyOn(mockTemplate, "registerInProject").and.callThrough();126 // const sourceFilesSpy = spyOn<any>(mockTemplate, "ensureSourceFiles");127 const mockLibrary = jasmine.createSpyObj("frameworkLibrary", ["hasTemplate", "getTemplateById"]);128 mockLibrary.hasTemplate.and.returnValue(true);129 mockLibrary.getTemplateById.and.returnValue(mockTemplate);130 addCmd.templateManager = jasmine.createSpyObj("TemplateManager", {131 getFrameworkById: {},132 getProjectLibrary: mockLibrary,133 updateProjectConfiguration: () => {}134 });135 spyOn(ProjectConfig, "getConfig").and.returnValue(mockProjectConfig);136 spyOn(ProjectConfig, "hasLocalConfig").and.returnValue(true);137 spyOn(addCmd, "addTemplate").and.callThrough();138 spyOn(PackageManager, "flushQueue").and.returnValue(Promise.resolve());139 spyOn(PackageManager, "ensureIgniteUISource");140 spyOn(Util, "directoryExists").and.returnValue(true);141 const mockVirtFs = {142 fileExists: () => {}143 };144 spyOn(App.container, "get").and.returnValue(mockVirtFs);145 spyOn(mockVirtFs, "fileExists").and.callFake(file => {146 if (file === "src/app/app-routing.module.ts") {147 return true;148 }149 });150 await addCmd.execute({151 name: "test-file-name", template: "CustomTemplate",152 // tslint:disable-next-line:object-literal-sort-keys153 module: "myCustomModule/my-custom-module.module.ts"154 });155 expect(addCmd.addTemplate).toHaveBeenCalledWith(156 "test-file-name", mockTemplate,157 jasmine.objectContaining({ modulePath: "myCustomModule/my-custom-module.module.ts" })158 );159 expect(PackageManager.flushQueue).toHaveBeenCalled();160 expect(mockTemplate.generateConfig).toHaveBeenCalledTimes(1);161 expect(mockTemplate.generateConfig).toHaveBeenCalledWith(162 "test-file-name",163 jasmine.objectContaining({ modulePath: "myCustomModule/my-custom-module.module.ts" })164 );165 expect(mockTemplate.registerInProject).toHaveBeenCalledTimes(1);166 expect(mockTemplate.registerInProject).toHaveBeenCalledWith(167 directoryPath, "test-file-name",168 jasmine.objectContaining({ modulePath: "myCustomModule/my-custom-module.module.ts" })169 );170 // expect(sourceFilesSpy).toHaveBeenCalledTimes(1);171 expect(routeSpy).toHaveBeenCalledTimes(1);172 expect(declarationSpy).toHaveBeenCalledTimes(1);173 expect(declarationSpy).toHaveBeenCalledWith(174 path.join(directoryPath, `src/app/test-file-name/test-file-name.component.ts`),175 true);176 expect(ngMetaSpy).toHaveBeenCalledTimes(1);177 expect(ngMetaSpy).toHaveBeenCalledWith({178 declare: null,179 from: "../test-file-name/test-file-name.component",180 // tslint:disable-next-line:object-literal-sort-keys181 export: null182 });183 expect(finalizeSpy).toHaveBeenCalledTimes(1);184 expect(addCmd.templateManager.updateProjectConfiguration).toHaveBeenCalledTimes(1);185 done();186 });187 it("Should properly accept module args when passed - Angular Wrappers", async done => {188 const mockProjectConfig = {project: {189 framework: "angular",190 theme: "infragistics"191 }};192 spyOn(TypeScriptUtils, "getFileSource").and.returnValue(193 ts.createSourceFile("test-file-name", ``, ts.ScriptTarget.Latest, true)194 );195 const routeSpy = spyOn(TypeScriptFileUpdate.prototype, "addRoute");196 const declarationSpy = spyOn(TypeScriptFileUpdate.prototype, "addDeclaration").and.callThrough();197 const ngMetaSpy = spyOn(TypeScriptFileUpdate.prototype, "addNgModuleMeta");198 const finalizeSpy = spyOn(TypeScriptFileUpdate.prototype, "finalize");199 const mockTemplate = new AngularTemplate("test");200 mockTemplate.packages = [];201 mockTemplate.dependencies = [];202 const directoryPath = path.join("My/Example/Path");203 spyOn(process, "cwd").and.returnValue(directoryPath);204 spyOn(mockTemplate, "generateConfig");205 spyOn(Util, "processTemplates").and.returnValue(Promise.resolve(true));206 spyOn(mockTemplate, "registerInProject").and.callThrough();207 spyOn(Util, "directoryExists").and.returnValue(true);208 // const sourceFilesSpy = spyOn<any>(mockTemplate, "ensureSourceFiles");209 const mockLibrary = jasmine.createSpyObj("frameworkLibrary", ["hasTemplate", "getTemplateById"]);210 mockLibrary.hasTemplate.and.returnValue(true);211 mockLibrary.getTemplateById.and.returnValue(mockTemplate);212 addCmd.templateManager = jasmine.createSpyObj("TemplateManager", {213 getFrameworkById: {},214 getProjectLibrary: mockLibrary,215 updateProjectConfiguration: () => {}216 });217 spyOn(ProjectConfig, "getConfig").and.returnValue(mockProjectConfig);218 spyOn(ProjectConfig, "hasLocalConfig").and.returnValue(true);219 spyOn(addCmd, "addTemplate").and.callThrough();220 spyOn(PackageManager, "flushQueue").and.returnValue(Promise.resolve());221 spyOn(PackageManager, "ensureIgniteUISource");222 await addCmd.execute({223 name: "test-file-name", template: "CustomTemplate",224 // tslint:disable-next-line:object-literal-sort-keys225 module: "myCustomModule/my-custom-module.module.ts"226 });227 expect(addCmd.addTemplate).toHaveBeenCalledWith(228 "test-file-name", mockTemplate,229 jasmine.objectContaining({ modulePath: "myCustomModule/my-custom-module.module.ts" })230 );231 expect(PackageManager.flushQueue).toHaveBeenCalled();232 expect(mockTemplate.generateConfig).toHaveBeenCalledTimes(1);233 expect(mockTemplate.generateConfig).toHaveBeenCalledWith(234 "test-file-name",235 jasmine.objectContaining({ modulePath: "myCustomModule/my-custom-module.module.ts" })236 );237 expect(mockTemplate.registerInProject).toHaveBeenCalledTimes(1);238 expect(mockTemplate.registerInProject).toHaveBeenCalledWith(239 directoryPath, "test-file-name",240 jasmine.objectContaining({ modulePath: "myCustomModule/my-custom-module.module.ts" }));241 // expect(sourceFilesSpy).toHaveBeenCalledTimes(1);242 expect(routeSpy).toHaveBeenCalledTimes(1);243 expect(declarationSpy).toHaveBeenCalledTimes(1);244 expect(declarationSpy).toHaveBeenCalledWith(245 path.join(directoryPath, `src/app/components/test-file-name/test-file-name.component.ts`),246 true);247 expect(ngMetaSpy).toHaveBeenCalledTimes(1);248 expect(ngMetaSpy).toHaveBeenCalledWith({249 declare: null,250 from: "../components/test-file-name/test-file-name.component",251 // tslint:disable-next-line:object-literal-sort-keys252 export: null253 });254 expect(finalizeSpy).toHaveBeenCalledTimes(1);255 expect(addCmd.templateManager.updateProjectConfiguration).toHaveBeenCalledTimes(1);256 done();257 });258 it("Should properly accept skip-route args when passed", async done => {259 const mockProjectConfig = {project: {260 framework: "angular",261 theme: "infragistics"262 }};263 spyOn(ProjectConfig, "hasLocalConfig").and.returnValue(true);264 spyOn(ProjectConfig, "getConfig").and.returnValue(mockProjectConfig);265 const mockTemplate = jasmine.createSpyObj("Template", {266 generateConfig: { test: "test" }, registerInProject: null267 });268 mockTemplate.templatePaths = ["test"];269 mockTemplate.packages = [];270 const mockLibrary = jasmine.createSpyObj("frameworkLibrary", {271 getTemplateById: mockTemplate, hasTemplate: true272 });273 addCmd.templateManager = jasmine.createSpyObj("TemplateManager", {274 getFrameworkById: {},275 getProjectLibrary: mockLibrary,276 updateProjectConfiguration: () => {}277 });278 const directoryPath = path.join("My/Example/Path");279 spyOn(Util, "processTemplates").and.returnValue(Promise.resolve(true));280 spyOn(process, "cwd").and.returnValue(directoryPath);281 spyOn(addCmd, "addTemplate").and.callThrough();282 spyOn(PackageManager, "flushQueue").and.returnValue(Promise.resolve());283 spyOn(PackageManager, "ensureIgniteUISource");284 await addCmd.execute({285 name: "test-file-name", template: "CustomTemplate",286 // tslint:disable-next-line:object-literal-sort-keys287 skipRoute: true288 });289 expect(addCmd.addTemplate).toHaveBeenCalledWith(290 "test-file-name", mockTemplate,291 jasmine.objectContaining({ skipRoute: true })292 );293 expect(Util.processTemplates).toHaveBeenCalledTimes(1);294 expect(PackageManager.flushQueue).toHaveBeenCalled();295 expect(mockTemplate.generateConfig).toHaveBeenCalledTimes(1);296 expect(mockTemplate.generateConfig).toHaveBeenCalledWith(297 "test-file-name",298 jasmine.objectContaining({ skipRoute: true })299 );300 expect(mockTemplate.registerInProject).toHaveBeenCalledTimes(1);301 expect(mockTemplate.registerInProject).toHaveBeenCalledWith(302 directoryPath, "test-file-name",303 jasmine.objectContaining({ skipRoute: true })304 );305 expect(addCmd.templateManager.updateProjectConfiguration).toHaveBeenCalledWith(mockTemplate);306 done();307 });308 it("Should not add component and should log error if wrong path is passed to module", async done => {309 spyOn(Util, "fileExists").and.returnValue(false);310 spyOn(Util, "error");311 const wrongPath = "myCustomModule/my-custom-module.module.ts";312 addCmd.addTemplate("test-file-name", new AngularTemplate(__dirname), { modulePath: wrongPath });313 expect(Util.fileExists).toHaveBeenCalledTimes(1);314 expect(Util.error).toHaveBeenCalledTimes(1);315 expect(Util.error).toHaveBeenCalledWith(`Wrong module path provided: ${wrongPath}. No components were added!`);316 done();317 });...
email-template.service.unit-spec.ts
Source:email-template.service.unit-spec.ts
1import { Test, TestingModule } from '@nestjs/testing';2import { UnprocessableEntityException } from '@nestjs/common';3import { EmailTemplateService } from 'src/email-template/email-template.service';4import { EmailTemplateRepository } from 'src/email-template/email-template.repository';5import { EmailTemplatesSearchFilterDto } from 'src/email-template/dto/email-templates-search-filter.dto';6import { CreateEmailTemplateDto } from 'src/email-template/dto/create-email-template.dto';7import { UpdateEmailTemplateDto } from 'src/email-template/dto/update-email-template.dto';8import { NotFoundException } from 'src/exception/not-found.exception';9import { ForbiddenException } from 'src/exception/forbidden.exception';10const emailTemplateRepositoryMock = () => ({11 getAll: jest.fn(),12 findOne: jest.fn(),13 countEntityByCondition: jest.fn(),14 updateEntity: jest.fn(),15 get: jest.fn(),16 createEntity: jest.fn(),17 paginate: jest.fn()18});19const mockTemplate = {20 title: 'string',21 slug: 'string',22 sender: 'string',23 subject: 'string',24 body: 'string',25 isDefault: false26};27describe('EmailTemplateService', () => {28 let service: EmailTemplateService, repository;29 beforeEach(async () => {30 const module: TestingModule = await Test.createTestingModule({31 providers: [32 EmailTemplateService,33 {34 provide: EmailTemplateRepository,35 useFactory: emailTemplateRepositoryMock36 }37 ]38 }).compile();39 service = module.get<EmailTemplateService>(EmailTemplateService);40 repository = module.get<EmailTemplateRepository>(EmailTemplateRepository);41 });42 afterEach(() => {43 jest.restoreAllMocks();44 });45 it('test slugify', () => {46 const result = service.slugify('Test Email');47 expect(result).toEqual('test-email');48 });49 it('get all email-templates', async () => {50 const filter: EmailTemplatesSearchFilterDto = {51 keywords: 'test',52 limit: 10,53 page: 154 };55 repository.paginate.mockResolvedValue('result');56 const results = await service.findAll(filter);57 expect(repository.paginate).toHaveBeenCalledTimes(1);58 expect(results).toEqual('result');59 });60 it('create email template', async () => {61 const createEmailTemplateDto: CreateEmailTemplateDto = mockTemplate;62 await service.create(createEmailTemplateDto);63 expect(repository.createEntity).toHaveBeenCalledWith(64 createEmailTemplateDto65 );66 expect(repository.createEntity).not.toThrow();67 });68 describe('find email template by id', () => {69 it('role find success', async () => {70 repository.get.mockResolvedValue(mockTemplate);71 const result = await service.findOne(1);72 expect(repository.get).toHaveBeenCalledTimes(1);73 expect(repository.get).not.toThrow();74 expect(result).toBe(mockTemplate);75 });76 it('find fail', async () => {77 repository.get.mockRejectedValue(new NotFoundException());78 await expect(service.findOne(1)).rejects.toThrowError(NotFoundException);79 });80 });81 describe('update email template by id', () => {82 let updateEmailTemplateDto: UpdateEmailTemplateDto;83 beforeEach(() => {84 updateEmailTemplateDto = mockTemplate;85 });86 it('try to update using duplicate title', async () => {87 repository.findOne.mockResolvedValue(mockTemplate);88 repository.countEntityByCondition.mockResolvedValue(1);89 await expect(90 service.update(1, updateEmailTemplateDto)91 ).rejects.toThrowError(UnprocessableEntityException);92 expect(repository.countEntityByCondition).toHaveBeenCalledTimes(1);93 });94 it('update email template that exists in database', async () => {95 repository.countEntityByCondition.mockResolvedValue(0);96 repository.updateEntity.mockResolvedValue(mockTemplate);97 repository.get.mockResolvedValue(mockTemplate);98 const role = await service.update(1, updateEmailTemplateDto);99 expect(repository.get).toHaveBeenCalledWith(1);100 expect(repository.updateEntity).toHaveBeenCalledWith(101 mockTemplate,102 updateEmailTemplateDto103 );104 expect(role).toEqual(mockTemplate);105 });106 it('trying to update email template that does not exists in database', async () => {107 repository.updateEntity.mockRejectedValue(new NotFoundException());108 repository.get.mockResolvedValue(null);109 await expect(110 service.update(1, updateEmailTemplateDto)111 ).rejects.toThrowError(NotFoundException);112 });113 });114 describe('remove email template by id', () => {115 it('trying to delete existing item', async () => {116 service.findOne = jest.fn().mockResolvedValue(mockTemplate);117 repository.delete = jest.fn().mockResolvedValue('');118 const result = await service.remove(1);119 expect(service.findOne).toHaveBeenCalledTimes(1);120 expect(service.findOne).toHaveBeenCalledWith(1);121 expect(service.findOne).not.toThrow();122 expect(repository.delete).toHaveBeenCalledTimes(1);123 expect(result).toEqual(undefined);124 });125 it('trying to delete no existing item', async () => {126 service.findOne = jest.fn().mockImplementation(() => {127 throw NotFoundException;128 });129 await expect(service.remove(1)).rejects.toThrow();130 expect(service.findOne).toHaveBeenCalledTimes(1);131 });132 it('delete default template test if throws error', async () => {133 service.findOne = jest.fn().mockResolvedValue({134 ...mockTemplate,135 isDefault: true136 });137 await expect(service.remove(1)).rejects.toThrowError(ForbiddenException);138 expect(service.findOne).toHaveBeenCalledTimes(1);139 });140 });...
html-loader.test.js
Source:html-loader.test.js
1import { html, fixture, expect, elementUpdated } from "@open-wc/testing";2import "../html-loader.js";3import { stub, assert } from "sinon";4describe("HtmlLoader", () => {5 const mockTemplate = {6 url: "./template.html",7 content: "<p>mock</p>",8 };9 beforeEach(() => {10 const fetchStub = stub(window, "fetch");11 fetchStub.withArgs(mockTemplate.url).returns(12 Promise.resolve(13 new Response(mockTemplate.content, {14 status: 200,15 headers: { "Content-type": "text/html" },16 })17 )18 );19 fetchStub.returns(20 Promise.resolve(21 new Response("", {22 status: 404,23 headers: { "Content-type": "text/plain" },24 })25 )26 );27 });28 it("import and render given template", async () => {29 const el = await fixture(30 html`<html-loader href=${mockTemplate.url}></html-loader>`31 );32 expect(el.href).to.equal(mockTemplate.url);33 assert.calledWith(window.fetch, mockTemplate.url);34 await elementUpdated(el);35 expect(el.innerHTML).to.equal(mockTemplate.content);36 });37 it("only load template after href attribute has been set", async () => {38 /** @type {HTMLLoaderElement} */39 const el = await fixture(html`<html-loader></html-loader>`);40 assert.notCalled(window.fetch);41 await elementUpdated(el);42 expect(el.innerHTML).to.equal("");43 el.href = mockTemplate.url;44 await elementUpdated(el);45 assert.calledWith(window.fetch, mockTemplate.url);46 expect(el.innerHTML).to.equal(mockTemplate.content);47 });48 it("load fallback if fetching href failed", async () => {49 const el = await fixture(50 html`<html-loader51 href="./nope.html"52 fallback=${mockTemplate.url}53 ></html-loader>`54 );55 assert.callCount(window.fetch, 2);56 assert.calledWith(window.fetch, "./nope.html");57 assert.calledWith(window.fetch, mockTemplate.url);58 await elementUpdated(el);59 expect(el.innerHTML).to.equal(mockTemplate.content);60 });61 it("render error message if fetching href failed and no fallback was available", async () => {62 const el = await fixture(63 html`<html-loader href="./nope.html"></html-loader>`64 );65 assert.calledWith(window.fetch, "./nope.html");66 await elementUpdated(el);67 expect(el.firstChild).to.have.class("html-loader__error");68 expect(el.firstChild.textContent).equals("(./nope.html) 404");69 });70 it("cache templates", async () => {71 const el = await fixture(72 html`<html-loader href=${mockTemplate.url}></html-loader>`73 );74 await elementUpdated(el);75 el.href = "./nope.html";76 await elementUpdated(el);77 el.href = mockTemplate.url;78 assert.calledTwice(window.fetch);79 assert.callOrder(80 window.fetch.withArgs(mockTemplate.url),81 window.fetch.withArgs("./nope.html")82 );83 await elementUpdated(el);84 expect(el.innerHTML).to.equal(mockTemplate.content);85 });86 afterEach(() => {87 window.fetch.restore();88 });...
Using AI Code Generation
1import { mockTemplate } from 'ng-mocks';2import { MyComponent } from './my-component';3describe('MyComponent', () => {4 it('should render the component', () => {5 const fixture = mockTemplate(MyComponent, '<my-component></my-component>');6 expect(fixture.nativeElement.innerHTML).toContain('Hello World');7 });8});9import { mockDirective } from 'ng-mocks';10import { MyDirective } from './my-directive';11describe('MyDirective', () => {12 it('should render the directive', () => {13 const fixture = mockDirective(MyDirective, '<div my-directive></div>');14 expect(fixture.nativeElement.innerHTML).toContain('Hello World');15 });16});17import { mockPipe } from
Using AI Code Generation
1import { mockTemplate } from 'ng-mocks';2import { mockProvider } from 'ng-mocks';3import { mockInstance } from 'ng-mocks';4import { mockDirective } from 'ng-mocks';5import { mockPipe } from 'ng-mocks';6import { mockProvider } from 'ng-mocks';7import { mockInstance } from 'ng-mocks';8import { mockDirective } from 'ng-mocks';9import { mockPipe } from 'ng-mocks';10import { mockProvider } from 'ng-mocks';11import { mockInstance } from 'ng-mocks';12import { mockDirective } from 'ng-mocks';13import { mockPipe } from 'ng-mocks';14import { mockProvider } from 'ng-mocks';15import { mockInstance } from 'ng-mocks';16import { mockDirective } from 'ng-mocks';17import { mockPipe } from 'ng-mocks';18import { mockProvider } from 'ng-mocks';19import { mockInstance } from 'ng-mocks';20import { mockDirective } from 'ng-mocks';21import { mockPipe } from 'ng-mocks';22import { mockProvider } from 'ng-mocks';
Using AI Code Generation
1import { mockTemplate } from 'ng-mocks';2import { createComponent } from 'ng-mocks';3describe('TestComponent', () => {4 let component: TestComponent;5 let fixture: ComponentFixture<TestComponent>;6 beforeEach(() => {7 fixture = createComponent(TestComponent);8 component = fixture.componentInstance;9 fixture.detectChanges();10 });11 beforeEach(() => {12 mockTemplate(TestComponent, '<div></div>');13 });14 it('should create', () => {15 expect(component).toBeTruthy();16 });17});18import { Component, OnInit } from '@angular/core';19@Component({20})21export class TestComponent implements OnInit {22 constructor() { }23 ngOnInit() {24 }25}26div {27 color: red;28}29import { async, ComponentFixture, TestBed } from '@angular/core/testing';30import { TestComponent } from './test.component';31describe('TestComponent', () => {32 let component: TestComponent;33 let fixture: ComponentFixture<TestComponent>;34 beforeEach(async(() => {35 TestBed.configureTestingModule({36 })37 .compileComponents();38 }));39 beforeEach(() => {40 fixture = TestBed.createComponent(TestComponent);41 component = fixture.componentInstance;42 fixture.detectChanges();43 });44 it('should create', () => {45 expect(component).toBeTruthy();46 });47});48import { async, ComponentFixture, TestBed } from '@angular/core/testing';49import { TestComponent } from './test.component';50describe('TestComponent', () => {51 let component: TestComponent;52 let fixture: ComponentFixture<TestComponent>;53 beforeEach(async(() => {54 TestBed.configureTestingModule({55 })56 .compileComponents();57 }));58 beforeEach(() => {59 fixture = TestBed.createComponent(TestComponent);60 component = fixture.componentInstance;61 fixture.detectChanges();62 });63 it('should create', () => {64 expect(component).toBeTruthy();65 });66});
Using AI Code Generation
1import { mockTemplate } from 'ng-mocks';2import { mockPipe } from 'ng-mocks';3describe('TestComponent', () => {4 let component: TestComponent;5 let fixture: ComponentFixture<TestComponent>;6 beforeEach(async(() => {7 TestBed.configureTestingModule({8 mockTemplate(ChildComponent, '<div>Mocked Child Component</div>'),9 mockPipe(TranslatePipe, 'Mocked Translate Pipe')10 })11 .compileComponents();12 }));13 beforeEach(() => {14 fixture = TestBed.createComponent(TestComponent);15 component = fixture.componentInstance;16 fixture.detectChanges();17 });18 it('should create', () => {19 expect(component).toBeTruthy();20 });21});
Using AI Code Generation
1import { mockTemplate } from 'ng-mocks';2describe('MyComponent', () => {3 it('should create', () => {4 const fixture = mockTemplate(MyComponent, '<my-component></my-component>');5 expect(fixture).toBeDefined();6 });7});8import { mockComponent } from 'ng-mocks';9describe('MyComponent', () => {10 it('should create', () => {11 const fixture = mockComponent(MyComponent);12 expect(fixture).toBeDefined();13 });14});15import { mockDirective } from 'ng-mocks';16describe('MyComponent', () => {17 it('should create', () => {18 const fixture = mockDirective(MyDirective);19 expect(fixture).toBeDefined();20 });21});22import { mockPipe } from 'ng-mocks';23describe('MyComponent', () => {24 it('should create', () => {25 const fixture = mockPipe(MyPipe);26 expect(fixture).toBeDefined();27 });28});29import { mockProvider } from 'ng-mocks';30describe('MyComponent', () => {31 it('should create', () => {32 const fixture = mockProvider(MyService);33 expect(fixture).toBeDefined();34 });35});36import { mockRender } from 'ng-mocks';37describe('MyComponent', () => {38 it('should create', () => {39 const fixture = mockRender(MyComponent);40 expect(fixture).toBeDefined();41 });42});43import { mockService } from 'ng-mocks';44describe('MyComponent', () => {45 it('should create', () => {46 const fixture = mockService(MyService);47 expect(fixture).toBeDefined();48 });49});50import { mockProvider } from 'ng-mocks';51describe('MyComponent', () => {52 it('should create', () => {53 const fixture = mockProvider(MyService);
Using AI Code Generation
1import { mockTemplate } from 'ng-mocks';2describe('TestComponent', () => {3 it('should create', () => {4 const fixture = mockTemplate(TestComponent, '<h1>Hello world!</h1>');5 expect(fixture).toBeTruthy();6 });7});
Using AI Code Generation
1import { mockTemplate } from 'ng-mocks';2describe('mockTemplate', () => {3 it('adds a component to the template', () => {4 const fixture = mockTemplate(MyComponent, '<div><my-component></my-component></div>');5 expect(fixture.nativeElement.innerHTML).toContain('<my-component></my-component>');6 });7});8import { Component } from '@angular/core';9@Component({10})11export class MyComponent {12}13import { ComponentFixture, TestBed } from '@angular/core/testing';14import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';15import { MyComponent } from './my-component.component';16describe('MyComponent', () => {17 beforeEach(() => MockBuilder(MyComponent));18 it('should create', () => {19 const fixture = MockRender(MyComponent);20 expect(fixture.point.componentInstance).toBeTruthy();21 });22});23import { ComponentFixture, TestBed } from '@angular/core/testing';24import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';25import { MyComponent } from './my-component.component';26describe('MyComponent', () => {27 beforeEach(() => MockBuilder(MyComponent));28 it('should create', () => {29 const fixture = MockRender(MyComponent);30 expect(fixture.point.componentInstance).toBeTruthy();31 });32});33import { ComponentFixture, TestBed } from '@angular/core/testing';34import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';35import { MyComponent } from './my-component.component';36describe('MyComponent', () => {37 beforeEach(() => MockBuilder(MyComponent));38 it('should create', () => {39 const fixture = MockRender(MyComponent);40 expect(fixture.point.componentInstance).toBeTruthy();41 });42});43import { ComponentFixture, TestBed } from '@angular/core/testing';44import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';45import { MyComponent } from './my-component.component';46describe('MyComponent', () => {47 beforeEach(() => MockBuilder(MyComponent));48 it('should create', () => {49 const fixture = MockRender(MyComponent);50 expect(fixture.point.componentInstance
Using AI Code Generation
1import { mockTemplate } from 'ng-mocks';2import { createComponent } from 'ng-mocks';3describe('Component: Test', () => {4 const mockData = mockTemplate({5 });6 const component = createComponent(mockData);7 it('should have a test paragraph', () => {8 expect(component).toBeTruthy();9 expect(component.querySelector('p').textContent).toBe('Test');10 });11});
Using AI Code Generation
1import { mockTemplate } from 'ng-mocks';2const fixture = mockTemplate('<div>Hello</div>', MyComponent);3const component = fixture.debugElement.componentInstance;4expect(component).toBeTruthy();5expect(fixture.debugElement.nativeElement.innerHTML).toContain('Hello');6import { Component } from '@angular/core';7@Component({8 <h1>{{title}}</h1>9 <p>{{text}}</p>10})11export class TestComponent {12 title = 'Hello';13 text = 'World';14}15import { mockTemplate } from 'ng-mocks';16const fixture = mockTemplate('<div>Hello</div>', TestComponent);17const component = fixture.debugElement.componentInstance;18expect(component).toBeTruthy();19expect(fixture.debugElement.nativeElement.innerHTML).toContain('Hello');20import { Component } from '@angular/core';21@Component({22 <h1>{{title}}</h1>23 <p>{{text}}</p>24})25export class TestComponent {26 title = 'Hello';27 text = 'World';28}29import { mockTemplate } from 'ng-mocks';30const fixture = mockTemplate('<div>Hello</div>', TestComponent);
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!!