![]() ![]() The JSON file and the geoip-lite module are just included to make the test use more memory so the issue becomes more obvious, but the tests will still leak even without them. The app just consists of a simple express server which requires a 7MB JSON file, imports the geoip-lite module, and includes Sentry for error logging. I put together a sample app that demostrates this issue at /chanind/jest-memory-leak-demo. ![]() node_modules/.bin/jest -runInBand -logHeapUsage to report how much memory is being used as your tests run. How can I tell if Jest is leaking memory?įortunately it’s easy to tell if your tests are leaking. Of course, you could also monkey-patch a native module somewhere in your own code and also trigger a memory leak. So, due to no code that you wrote yourself, your Jest tests can start leaking memory. Error logging / analytics modules tend to do this sort of decorating of native modules, but theoretically any module can do it. You can find more discussion in this Jest Github issue.Īll it takes to trigger your tests to leak is to require a third-party module that decorates a native module anywhere in your code. ![]() Then anything that module references will also stick around in memory, and so on until everything in your entire test suite is floating around in memory after the test finishes. If a non-native module that you require decorates or monkey-patches a native module, that module will end up sticking around in memory between tests. However, Jest’s ability to reset the require cache only goes so far - it can’t properly reset native modules like fs or https, for example. So, even if test suite A requires a module and modifies that module, test suite B can still import that same module and have its own separate copy. This is really nice because it gives test suites complete isolation from each other. Jest resets the require cache between each test run. Even if you don’t use Jest, it’s still useful to understand the process in case you need to debug memory leaks in other javascript code. In this article, we’ll walk through why it’s so easy for Jest to leak memory, how to tell if your tests have a memory leak, and then how to debug and eliminate leaks in your tests. That is, until you add one more test and suddenly the suite comes apart. For many test suites this isn’t a problem because even if tests leak memory, the tests don’t use enough memory to actually cause a crash. Jest is designed in a way that makes memory leaks likely if you’re not actively trying to squash them. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
December 2022
Categories |