Please note that @testing-library/user-event version 14 has made all APIs async and the workshop material has been updated to use the latest version of that package. So you'll need to make all tests async and use await when using that package.

Transcript

Kent C. Dodds: 0:00 Sometimes you have code that you don't want to have run, or maybe you have code that won't run in the specific environment that you're testing in. This is where I let you in on a little secret.

0:12 We're not running our test in a real browser. They're a simulated browser in Node using a module called jsdom. Sometimes there are things that jsdom isn't able to do that you have to just fake out.

0:27 For example, matchMedia, which is supported on Windows is not supported in jsdom. You have to include a polyfill for that and then also, we monkey-patch-resize too on Windows so that we can test out things that rely on matchMedia. That's just one of several examples of APIs that jsdom which you might need to test for your particular application.

0:53 There is another reason to mock things out and that is if a module is doing something that you don't want it to do for your test, and here I give you an example of how you would go about doing that using Jest APIs which are extremely powerful.

1:09 Feel free to dive in and get an idea of how that all works and how to use it effectively. For our exercise, we've got an API, window.navigator.geolocation, which is not supported in jsdom. We're using a library that uses getCurrentPosition to get the user's current location.

1:28 The example that we're looking at is this location example. When you go there, it's going to ask for your location, and while it's waiting, it's going to show this loading spinner here. You click Allow, and then it will show you your latitude and longitude. We want to test this functionality in our component test which are running in Jest with jsdom, which of course does not support the getCurrentPosition API.

1:52 For the exercise, you're going to be implementing a getCurrentPosition API to mock that out so that our third-party library will be able to call it without any trouble. For the extra credit, we're going to try mocking out that module instead, and you can decide which one of those approaches you like more.

2:09 This one's a little bit on the tricky side, but I think that you can do it and the emoji are there to help. Have a good time, and we'll see you on the other side of the exercise.