![]() In our first example, the library exports is a single default function. All of those choices affect how the package needs to be mocked in the tests of our application code.īelow, we'll look at some tiny examples to highlight how different exports change our mock strategy. When publishing a package, the maintainer makes decisions such as choosing default or named exports and whether to export a vanilla function, an object, or a function that returns an object of other functions. ES6 Exportsīefore we worry about our mock's behavior, it's important to understand how the package we're using is exported. It's a React app with Jest as the test runner and uses React Testing Library to test the component DOM (this is the default configuration with Create React App).ĭespite being built with React, the mocking examples should be easily portable to any framework. The sample application shows you a random cute image of an animal every 3 seconds. What do we want the behavior of our mock to be?Īll of the following code samples can be found on my Github.When mocking a module or function, there are 2 main things to consider: This is not an exhaustive list, there are multiple ways to satisfy every use case. I created this post to serve as an easily navigable guidebook of strategies for the next time jest.mock('modulename') won't cut it. Recently, I've been spending more time wrestling with uncooperative mocks than writing the code or the tests combined. Warning: An update inside a test was not wrapped in act.Cannot set property of # which has only a getter. ![]() ![]() Cannot spy the default property because it is not a function.The module factory of jest.mock() is not allowed to reference any out-of-scope variables.Named export of a function that returns an object.Default export of a function that returns an object. ![]()
0 Comments
Leave a Reply. |