Subscribe: Jeffry Houser's Blog
Added By: Feedage Forager Feedage Grade B rated
Language: English
angular  code  component  directory  gulp script  gulp  java  maven  project  royale  run  script  test  unit test  unit 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Jeffry Houser's Blog

Jeffry Houser's Blog

Jeffry Houser's Blog

Published: Mon, 23 Apr 2018 18:10:35 -0600

Last Build Date: Wed, 18 Apr 2018 09:00:00 -0600


How do I test Observable.timer?

Wed, 18 Apr 2018 09:00:00 -0600

This was trickier than I thought, which is why I'm writing a blog post about it. I'm writing some code which uses an FakeAsync Zone nor RxJS TestScheduler. The timer() call returns an Observable, so I decided to create one myself which gave me complete control. let timerObserver :Observer; beforeEach(() => { spyOn(Observable, 'timer').and.returnValue(Observable.create( (observer =>{ timerObserver = observer; }) )); }); I created an Observer object. This is the internal logic that makes the Observable resolve itself. I used spyOn() inside a beforeEach() to have the unit testing framework return my own Observable and ignore the library code. I save the observer for later usage. Now, when I'm testing I can resolve the timer immediately: it('Some Test',()=>{ // do stuff if needed // trigger the fake timer using the Observer reference''); timerObserver.complete(); // expect(somethingToHappenAfterTimerCompletes).toHaveBeenCalled(); }); I spent more time banging my head on this than I thought I would, and I hope this helps you.

How do I test the text of an HTML Element with Jasmine, Karma, and Angular?

Wed, 11 Apr 2018 09:00:00 -0600

I think this should have been simple, but my Google Fu was failing me. I'm working on an Angular app, as I often do, and was writing unit tests to verify that property changes inside a Component's class were reflected inside the view template.

The Component and View

I'm just going to use truncated code here, but the component had a property like this: export class MyClass{ @Input() buttonText : string = ""; } The template had something like this: Change the value on the component, and the view should change. This sort of binding is basic to Angular. How do we test that?

Write the Tests

First, you set up the TestBed: beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ MyComp ] }) .compileComponents(); fixture = TestBed.createComponent(MyComp); component = fixture.componentInstance; })); This should be pretty standard, and this code is almost copied verbatim from the Angular CLI defaults. Now your test should do something like this. First set the value on the component const defaultButtonText = "Something" component.buttonText = defaultButtonText ; Now you have to detect the changes to force the view to refresh itself: fixture.detectChanges(); Get the HTML Element: const button = fixture.debugElement.query(By.css('.myButton')); And check the button's TextContent: expect(button.nativeElement.textContent.trim()).toBe(defaultButtonText ) You're code should be all set to test. For completeness, here is the full test: it('Set Button Text to Something', () => { const defaultButtonText = "Something" component.buttonText = defaultButtonText ; fixture.detectChanges(); const button = fixture.debugElement.query(By.css('.myButton')); expect(button.nativeElement.textContent.trim()).toBe(defaultButtonText ) }); I hope this helps someone.

How do I listen for an Angular Event in TypeScript?

Tue, 03 Apr 2018 09:00:00 -0600

I'm building a custom Angular service for a client project that will create modal and other popups. If certain interaction occurs within the modal, then the modal should dispatch an event and the service needs to close the modal. In Angular you can use an EventEmitter to dispatch the event from the component's class. Create the emitter as a property on the component's class and add the @output metadata: @Output() myEvent : EventEmitter = new EventEmitter(); Then to dispatch the event use the emit method: this.myEvent.emit('Emitted Value'); That does exactly what I need in the component side. However, to listen for the event, most of the documentation I can find talks about doing so in the HTML template: Unfortunately, the service cannot add that event handler onto HTML because there is no HTML, so that was a no go for my use case. How do you do it? After the service creates the component and displays it, it has an instance to that component class. We can introspect into the component class to get access to the emitter, and subscribe to it: myCompRef.instance.myEvent.subscribe((value) => { // do something }); Under the hood the EventEmitter is a Subject, which is like an Observable.

Running Unit Tests from IntelliJ

Sat, 31 Mar 2018 21:25:00 -0600

I put together this screencast about running Unit Tests using IntelliJ. width="560" height="315" src="" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen>

How do you tell Jasmine to run a single test?

Thu, 22 Mar 2018 09:00:00 -0600

Last week I wrote about how to tell Jasmine to ignore a unit test. This week I'll tell you how to ignore every unit test except one. To use last week's example, a normal unit test would be something like this: it("True is True", () =>{ expect("True").toBe("True"); }); A normal test suite will include lots of tests spread out through lots of files. You can focus a unit test using fit(). This tells Jasmine to only run the unit test with the 'f': fit("True is True", () =>{ expect("True").toBe("True"); }); other unit tests will be ignored. This can be a great use when testing something new. You can use the same thing to disable a full suite with fdescribe() instead of describe: fdescribe("Some Test Suite"()=>{ it("True is True", () =>{ expect("True").toBe("True"); }); }); This type of stuff can be pretty handy if you're running your tests via command lines.

How do I tell Jasmine to ignore a test?

Wed, 14 Mar 2018 11:20:00 -0600

Today I learned you can tell Jasmine to ignore a unit test. A normal unit test would be something like this: it("True is True", () =>{ expect("True").toBe("True"); }); When running a unit test file with this inside the test will run., You could comment it out if you wish, but that can get confusing for larger unit tests with embedded oomments. Instead you can use xit() instead of it(): xit("True is True", () =>{ expect("True").toBe("True"); }); Now when you run your unit test, this test will be marked as viewed as pending and will not be run. You can use the same thing to disable a full suite with describe(): xdescribe("Some Test Suite"()=>{ it("True is True", () =>{ expect("True").toBe("True"); }); }); This is pretty handy, but something I overlooked when learning all about unit testing.

How to I make my Angular Component Styles global?

Sat, 10 Mar 2018 11:46:00 -0600

An awesome thing about building Angular components is that the styles you specify are 'local' to the component. In normal HTML development, any style on the page can affect any other style. For example. If I add a style like this: div { border:1px solid red; } Every div in the site / application will have a solid red border. Check out a sample here. If you build an Angular, component, and that style is only included in the application as part of the component, then only that component's div will given a solid color red border. The reason for this is because Angular creates something they call a Shadow DOM. Under the hood it is some coding magic to conditionally apply styles only to the component in question, not to other components. However, Angular allows us to change this behavior using something called ViewEncapsulation. A default Angular component is like this: @Component({ selector: 'my-comp', templateUrl: 'my-comp.component.html', styles: [`my-comp.component.css`], encapsulation: ViewEncapsulation.Emulated }) The Emulated value means that Angular will simulate a Shadow DOM. This is considered safest because not all browsers support their own shadow DOM trees. In most cases, I use this approach and leave out the encapsulation attribute. I like to have my styles encapsulated to a single component. But that is not required. There are two other options: @Component({ selector: 'my-comp', templateUrl: 'my-comp.component.html', styles: [`my-comp.component.css`], encapsulation: ViewEncapsulation.Native }) The Native property tells Angular to use the browsers Shadow DOM. In this case, styles are encapsulated just like they would be in the emulated approach. So, any styles in the my-com-componment.css file will affect all HTML elements globally. To turn off style encapsulation complete, use the None value from the ViewEncapsulationclass: @Component({ selector: 'my-comp', templateUrl: 'my-comp.component.html', styles: [`my-comp.component.css`], encapsulation: ViewEncapsulation.None }) I'm working on my second super really big Angular application for a client, and it is giving me the opportunity to touch on areas I normally wouldn't.

The Learn With Series now includes Java and PHP

Sat, 03 Mar 2018 21:50:00 -0600

The Learn With series now includes a few new book that talk about integrating with Java or PHP. Check them out now. I'm greatly enjoying writing these books, experimenting with different technologies, and taking you all along for the ride.

Setting up Java and Jersey with IntelliJ

Sat, 24 Feb 2018 19:23:00 -0600

I put this video together about setting up Java and Jersey using IntelliJ. This demonstrates the project structure I used when writing the Learn With books on Java. width="560" height="315" src="" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen>

What is the difference between Boolean class and boolean primitive type in Java?

Sat, 17 Feb 2018 08:31:00 -0600

I was recently working on the Java code for the LearnWith series. The application behind the book is a Task Manager application and one of the features is the ability to filter tasks based on their completed state. The database field is a bit field, because a task can either be completed or not completed. However, from a filtering perspective I need to accommodate for three different states: Completed, not Completed, and All Tasks. How do I handle that in Java? A database bit column usually turns into a Boolean value in a programming language, and for that it works great. With Java the boolean primitive type is perfect for this. It can support values of true or false. However, boolean does not have an undefined or null state. It must always have a value. To handle the UI filtering I had to use an instance of the Boolean class. Since it is a class it can be undefined or null. The final code was something like this: if(BooleanVariable != null){ // do something to handle value } else { // do something to handle the null value } This stuff should be old hat if you have a lot of Java experience, but from someone who focuses on UI code over server side code, it made me pause for 10 seconds to figure it out.

How do I run ES6 JavaScript code on the console?

Thu, 08 Feb 2018 17:19:00 -0600

I've been following a tutorial on using Redux and the code in the sample is ES6 code. The tutorial ran the code in the debugger of Visual Studio Code, but me being an IntelliJ user could not find an parallel way to run the code. I created an Index.html file that loaded the JS file, but nothing happened. I assume because the ES6 syntax used in the sample as not yet universal in the browser JS engines. So, what next? I looked for a way to run the code at the console, and found one. With NodeJS installed: node filename That ran the code, and gave the same results that the tutorial got in the Visual Studio Code window. After doing that, I realized I could run the same thing in IntelliJ's terminal Window. I'm not used to running advanced JS or TypeScript code w/o transpiling it with a tool like TypeScript, Webkit or the Angular CLI. This project started simpler, but I'm good to go now. I hope this helps you!

Why can't IntelliJ find java.time with JDK 9?

Thu, 01 Feb 2018 09:00:00 -0600

I've been working on a a few projects that use the JDK 9 with IntelliJ. My latest started getting an error like this: java package java.time does not exists java cannot find symbol symbol: class LocalDate The LocalDate class was added to the JDK 8, so this error makes sense if you are building using an earlier version of JDK. But, I should not be seeing it when using JDK 9. Googling on similar errors seems to bring me back to the same thing I already knew. You're using the wrong version of the JDK, be sure to upgrade to JDK 8 or later. But, I am already using JDK 9, so should not be having this problem. I spent an hour pouring over IntelliJ settings before stumbling onto this screen: (image) The Java Compiler target bytecode version of my project was set to 1.7 instead of 9. I already fixed that in the screenshot above. It made my errors go away immediately. The most confusing thing is that I didn't have errors on any of the other projects.

What is Apache Royale?

Tue, 23 Jan 2018 10:00:00 -0600

A friend reached out to me to ask what I thought of Apache Royale and I thought it would make a good blog post.

What is Apache Royale?

Apache Royale is a rebrand of Apache Flex's FlexJS project. Royale would allow you to create HTML(5) applications with MXML and ActionScript. It is independent and separate from Adobe's Flash Platform. There are a lot of 'legacy' Flex apps out there, so from that perspective it makes a lot of sense to allow a Flex Developer to repurpose their AS3 and MXML skills in order to build HTML5 applications with no reliance on the Flash Player or Adobe AIR. That is great.

Where do I fit in?

While I am still a PMC member of the Apache Flex project, I am not involved with Royale in any way. I haven't followed Apache Royale very closely, and am even less so since it was promoted to a top level Apache project, separate from Flex. You can take my opinion and understanding with a grain of salt.

What do I think about Royale?

Despite the impressiveness of the technology, Royale does not allow you to convert a Flex application to an HTML5 application. It is expected you will create a new application from scratch. And since you're doing that regardless, why not use a technology that is more 'native' to HTML(5) development? Such technologies might be AngularJS or React. I fear the target market of Royale--Flex Devs who want to build HTML5 applications--moved on many years ago. The flip side of that is that HTML5 devs change their mind on the framework of choice every few years. They have embraced ActionScript-like things such as TypeScript and frameworks built with it such as Angular. These are clearly not as HTML5 'native' like AngularJS or React are. Could the tide of interest swing back to ActionScript and MXML? I don't know.

Final Thoughts

While Apache Royale is a really cool project, I fear it is too little too late. I don't have any problems building HTML5 applications that would be solved by moving to a MXML / ActionScript solution. There are already other frameworks and tools for converting from ActionScript to JavaScript, but they have not gained a lot of traction. I see no reason why Royale would change that. I do wish the team luck, they have some of the smartest people I had the privilege of knowing. For now I'm content building Angular applications to solve client problems.

How do I copy files with Maven?

Tue, 16 Jan 2018 09:00:00 -0600

Last week, I wrote about running a Gulp Script from Maven. The Gulp Script was located in a directory outside of the Java project. This week I'll show you how to copy the file from the external directory into the Java project. We're going to use the maven-resources-plugin to make this work. First, set it up as a plugin in the Maven POM file: maven-resources-plugin 3.0.2 This adds the artifactId--AKA the plugin name--and the version number. For each set of files we want to copy, we'll need to add an execution block, so start there: copy-resources-A5 validate copy-resources This specifies the id of the copy, which is just a unique name for the process. It is done on the validation phase. And the goal is to copy-resources. Before we end the execution block, we need to add the configuration. this will tell us what we are copying and where we are copying it too. ${basedir}/src/main/webapp/A5 C:/Projects/lw/A5/chapter7/Angular5TypeScript/build true The outputDirectory specifies the location of the copied files. I made them relative tot he $(basedir), which is the root of the Java project. In the Angular 5 files in the A5 directory of the Java Project's webapp. The source directory is listed under resources, resource. Finally close off the open tags, which is the execution tag, the executions tag, and the plugin tag: I'm using this approach to copy the results of an external Gulp script into the final WAR, so that the files will be surfable via the Tomcat instance. It has been working great for me.

How do I run a Gulp Script in a different directory from Maven?

Tue, 09 Jan 2018 09:00:00 -0600

If you want to run a Gulp Script from Maven, you use the frontend plugin, right? Unfortunately, that seems to assume that the Gulp script is part of the Java project. I'm creating a Java Backend to the LearnWith series and am sharing UI code between multiple backend technologies. As such, my directory structure is different and the UI code is not in the web root. I want to run a gulp script in a different directory, and then copy the results into the project's webapp directory. How do you do it? I was able to do it with the exec Maven Plugin. First, set up the plugin in the plugins portion of Maven POM: org.codehaus.mojo exec-maven-plugin 1.6.0 The groupId, arftifactId, and version are specified. For each script you want to run you'll need an execution statement: Build Angular 5 validate exec gulp build C:\Projects\lw\A5\chapter7\Angular5TypeScript The id is a unique name for the build script. The phase is validate, because it is. The goal should be set to exec. The configuration is where the real magic happens. We tell it to execute the gulp command with the argument 'build', so this will run: gulp build We want to make sure that the script runs in the proper directory and that is specified with the workingDirectory tag. Presumably this directory will be outside the current directory structure. Finally, close the plugin tag: That's all you need to do to run an external Gulp Script from a Maven project. This assumes, of course, you have Gulp installed. Next week I'm going to write about copying the processed files into the Java project.