Angular Core Angular Core

Unit Testing a Component Method

Check out a free preview of the full Angular Core course:
The "Unit Testing a Component Method" Lesson is part of the full, Angular Core course featured in this preview video. Here's what you'd learn in this lesson:

Lukas live codes a test to see if a component method is operating correctly.

Get Unlimited Access Now

Transcript from the "Unit Testing a Component Method" Lesson

[00:00:00]
>> Lukas Ruebbelke: So every property or method that's on your component, you now have access to, and now you can test, like, is this property set? Can I call this property? For instance, if we go to projects.component, let's look at selectProject. So now, if we go back here, we could do something like, it 'should select a project'.

[00:00:39]
>> Lukas Ruebbelke: And what we can do is we can go component.selectProject.
>> Lukas Ruebbelke: So I'm jumping around here.
>> Lukas Ruebbelke: And If I go in here, we have this emptyProject. So I'm just going to pick this up, and because I may want to use this again, I'm just going to paste this in the top of my test spec.

[00:01:18] It kind of is like, do I put it in kind of at the top? Do I make it generally available? Do I just recreate it every single time? And I don't have a strong opinion on that. Typically, if something becomes super annoying, if I'm sick of recreating this same thing over and over, then I'll basically promote it to the general test spec.

[00:01:35] Or even, if you're doing something over and over, and over, you may promote that to a mock. And so there's some ways to, depending on how you're using it, then promote it for reuse. Which you'll also see quite frequently, is some utility classes for generating some of this mock stuff.

[00:01:57] So a lot of times people will create some utilities that I know there are exist utilities for. I'm not even gonna hard code this, I'm just going to call a factory, and it's gonna generate something for me. So now what we can say is, when I call selectProject and I pass in emptyProject, or we're going to call this.

[00:02:19] And now when do this, what do we expect? Well, we expect that component.selectedProject toBe emptyProject. Now, I make it bit here because I'm never quite sure toBe or toEqual, one is strict and one is not. But if this fails, then we'll just switch it to toEqual and that should work.

[00:02:53]
>> Lukas Ruebbelke: I'm in suspense.
>> Lukas Ruebbelke: All right, so in the projects.component it should select a project. So this actually passed, and so I'm feeling super good about myself.