JavaScript Testing Practices and Principles

Asserting Calling a Mock Exercise

Kent C. Dodds

Kent C. Dodds

Professional Trainer
JavaScript Testing Practices and Principles

Check out a free preview of the full JavaScript Testing Practices and Principles course

The "Asserting Calling a Mock Exercise" Lesson is part of the full, JavaScript Testing Practices and Principles course featured in this preview video. Here's what you'd learn in this lesson:

In this exercise, students are to gain more confidence out of a mock by asserting that it is being called in the way that is expected.

Preview
Close

Transcript from the "Asserting Calling a Mock Exercise" Lesson

[00:00:00]
>> Kent C. Dodds: So if you jump into thumb-war.2.todo, here we have the solution. We're going to make sure that this function that we have, this getWinner function, is called in the way that we expect it to be called. So that if somebody were to come in here and try to refactor this with a game argument or something.

[00:00:26]
That we can have some sort of validation to make sure that that would actually fail our test, unless somebody went to update the test, as well. So yeah, that's a whole idea we need. The way that I suggest in the hints of how to do this is to add a property to the getWinner function.

[00:00:46]
So something as simple as getWinner.mock.calls, that'll be your array. So you'll need to create that mock object and things. And then every single time this getWinner function is called, you'll want to also return p2, but you'll want to push on to that call's array. So go ahead and give this a shot.

[00:01:05]
In addition to keeping track of how many calls it has and all of that, you'll also want to make assertions on how it's being called as well. So you've got that stuff here. Yeah, so to run these tests you'll want to hit the P key. And just watch mode and do thumb-war.2.todo to get these tests ran.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now