Check out our Angular Book Series.

How do I test Observable.timer?

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<any>;
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.next('');
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?

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:


<button class="myButton">{{buttonText}}</button>

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?

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<any> = 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:


<MyComp
(myEvent)="onMyEvent($event)">

</MyComp>

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

I put together this screencast about running Unit Tests using IntelliJ.

How do you tell Jasmine to run a single test?

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?

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?

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

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

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.

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

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.

More Entries

All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.