Running Jest tests loop forever - unit-testing

Today, for some unexplained reason my jest test files started looping, resulting in a flickering terminal.
I am running jest src --watch, src being my source folder.
I followed a number of other discussions but none of them have helped solve my issue.
https://github.com/facebook/jest/issues/4635 is talking about a custom processor, but I am using a default setup.
I have tried ignoring folders.
I have ended up removing all my test files, at which point the looping stops. If I add a test file to __tests__ it matches the file but does not run a test. If I add the test file to my /src folder, it starts looping again, and it doesn't matter if the actual test passes or fails. Even if I add a fake test with a simple
describe('Test Suite', () => {
test('two plus two is four', () => {
expect(2 + 2).toBe(4)
})
})
it loops and flickers.
This is my jest setup
"jest": {
"verbose": false,
"watchPathIgnorePatterns": [
"<rootDir>/dist/",
"<rootDir>/node_modules/"
],
"globalSetup": "./jest-setup.js",
"globalTeardown": "./jest-teardown.js",
"testEnvironment": "./jest-mongo.js"
},
Does anyone know what is causing this to loop? I am not changing any files in any folder to make the --watch think it needs to run again, there are no other apps i.e. dropbox syncing the folder.
I am developing in VSCode, but the same thing happens if I test in a terminal window.
This was running fine just 5 hours ago, what went wrong?

It turns out that the jest.setup file was writing a configuration file to disk, while setting up a temporary mongoDB. If at least one of the tests used the mongoDB the looping stopped, or if I removed the setup files the looping stopped.
So my problem started when out of 30 test files, the one that connected to mongo was edited (starting the looping/flickering). In trying to solve the problem I removed all the rest of the test files, which left me with the most basic tests, but still the looping because I was still not connecting.
Still not 100% sure of the exact mechanism, but when inheriting someone else's codebase which doesn't use the default jest setup, probably best to expand jest knowledge to understand what's going on.

Related

jest manual ES6 class mock is not active and I want to understand why

I am having problems using Jest manual mocks (the one in a parallel __mocks__ directory) in my project.
I think I understand how to use it and it actually works fine if I remove a single line in a file specified in the Jest setupFiles array.
In that file a global helper is installed (into global.createComp) that uses the vuex store.
This is a vue + vuex project but even running the stripped down spec using only jest gives unexpected results.
Can somebody look at my minimal reproducible example repo at https://github.com/thenoseman/jest-manual-mock-not-working, do a npm i and npm run test:unit and help me understand why the mock is not active?
You can find the line that need to be commented out in test/unit/support/helpers.js.
Also the README shows a screenshot and further explains what the problem looks like.
setupFiles are evaluated before test files. As the reference states,
A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself.
JavaScript modules are evaluated once on first import. Importing #/store/modules/internetAtHome in helpers.js results in importing original #/api/DslService.
The mock in test file doesn't affect #/api/DslService because it has already been evaluated earlier:
jest.mock("#/api/DslService");
import DslService from "#/api/DslService";
In case helpers.js needs mocked #/api/DslService, jest.mock needs to be moved there.
In case helpers.js needs original #/api/DslService but tests need mocked one, the module (and any module that depends on it) needs to be re-imported with jest.resetModules or jest.isolatedModules:
jest.mock('#/api/DslService');
let DslService;
jest.isolateModules(() => {
DslService = require("#/api/DslService").default;
});
...
For a module that was imported with original implementation and needs to be re-imported as a mock, jest.requireMock can be used, it doesn't need jest.mock('#/api/DslService'):
let DslService = jest.requireMock("#/api/DslService").default;
...

Postman-Run a folder issue

Im using latest version of Postman v5.3.2
When running a folder with several requests inside of it, it is not executing them sequentially in the same order they appear in the main app. unlike when running the all collection that contains that folder.
Is this a bug or Postman do not support this?
When you need to run anything sequentially through the Collection Runner, you need to add logic to the "Tests" tab in your request.
There is a built-in method call "setNextRequest" that you can use in this situation. (documentation: https://www.getpostman.com/docs/postman/collection_runs/building_workflows) It's important to note that "setNextRequest" only runs when you use the Collection Runner. (not sure if this is a bug, or as intended)
Here is an example I made: https://www.getpostman.com/collections/78ffebd7823f47b26a21
In this example collection, you can see that Test checks for status 200, then if true, calls Test3 using setNextRequest on line 3. The same is done inside of Test3 on line 3, but we call Test2 instead. In Test2 we again run a test, but this time we're STOPPING the execution by supplying null to the method.
Note: you MUST to supply null as an argument to setNextRequest in Test2 to prevent the collection from running over and over.
The results in the Collection Runner should look like this:
Hope this helps someone.

Race condition with Jest

I am testing my graphql endpoint that is doing query to DB through sequelize with Jest. But sometimes I found my test files kind of having a race condition. What I mean is, for every test file I have a setup DB block such as
beforeAll(async () => {
await database.sequelize.sync({force: true})
await database.User.create(user)
})
so that in the test file I can easily predict what is in DB. Sometimes this causes an issue where every test file trying to do .sync(). One test file will create DB while the other performs drop DB.
Even though I have used await through out my tests, this doesn't look like guarantee that the test file will wait for another test to finish.
What would be the best approach here to make sure every test file can predict what is in DB by having clean DB while at the same time not conflicting with other tests? Is it actually a good idea for a test to wait for others to finish? It seems not optimised to me as it will take more time to run the whole test suite.
How many workers are you using? Tests run serially within the same test file, but not between different test files.
There are a number of options to try:
1 - Creating and using a unique DB for every test file.
2 - Making them all run serially with the --runInBand flag. I'm not sure but maybe --maxWorkers=1 does it as well.

Jest React Example

I am trying to run the React Example from the Jest React tutorial but I am receiving errors
λ npm test
> ...
> jest
Found 1 matching tests...
FAIL __tests__\CheckboxWithLabel-test.js (0.551s)
npm ERR! Test failed. See above for more details.
npm ERR! not ok code 0
I have pretty much copied the code directly from the example. The package.json is as follows:
{
"dependencies": {
"react": "*",
"react-tools": "*"
},
"scripts":{
"test": "jest"
},
"jest": {
"scriptPreprocessor": "<rootDir>/preprocessor.js",
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react"
]
},
"devDependencies": {
"jest-cli": "~0.1.17"
}
}
Any thoughts on what I can do to resolve these errors and run the example test successfully? It's very possible I'm missing an important detail (or details) but not entirely sure what. Oh and for what it's worth, I'm running this on Windows if that impacts this. I would really like to get some tests on my react components (was having some trouble there too so started with the basic examples) -- any help would be appreciated :)
I created an issue on their github page. Waiting to find out if it is actually a windows related issue
In the meantime, eventually got it working by just specifying the name of the module rather than the relative path
"unmockedModulePathPatterns": ["react"]
To anybody who ends up here on a search about this, #ron's github issue was ultimately resolved, and the conclusion was that unmockedModulePathPatterns expects an array of regex statments matching file paths, not necessarily the file paths themselves. This is why using the "relative" paths worked. From the Jest API docs:
An array of regexp pattern strings that are matched against all
modules before the module loader will automatically return a mock for
them. If a module's path matches any of the patterns in this list, it
will not be automatically mocked by the module loader.
This is useful for some commonly used 'utility' modules that are
almost always used as implementation details almost all the time (like
underscore/lo-dash, etc). It's generally a best practice to keep this
list as small as possible and always use explicit
jest.mock()/jest.dontMock() calls in individual tests. Explicit
per-test setup is far easier for other readers of the test to reason
about the environment the test will run in.
It is possible to override this setting in individual tests by
explicitly calling jest.mock() at the top of the test file.
(https://facebook.github.io/jest/docs/api.html#config-unmockedmodulepathpatterns-array-string)
and from the issue itself:
unmockedModulePathPatterns are used internally by Jest to create a
RegExp against which all required modules will be tested. As such, you
need to provide a valid regex pattern. For example, this worked nicely
for me :
> unmockedModulePathPatterns: [
> "node_modules\\" + path.sep + "react",
> "node_modules\\" + path.sep + "reflux",
> "node_modules\\" + path.sep + "react-router"
> ],
"mlarcher", (https://github.com/facebook/jest/issues/100)
<rootDir> should be replaced with the actual path. It looks like you don't have a subdirectory you want to start from, whereas in some cases you might only want to run tests in a src/ path so your package.json would look more like this:
{
...
"jest": {
"rootDir": "src",
"scriptPreprocessor": "../jest/preprocessor.js" // Note: relative to src
}
...
}

Using EmberJS, Mocha and Karma

I am using Mocha and Karma for writing and running test cases for my emberjs client. I bundle all my test cases as a single file and using minispade.js to solve the dependency issues
The problem which I am facing is that, I am able to run the test cases, but if a test case fails, it only shows the description of the test case and does not provide any info about the file which has the case written.
Is there any way to show the file name also, if any test case fails?
#stevekane,
Are you invoking your client's code ( ie. minispade wrapped files) in your test-case module using minispade.require()?
Here is how I have used minispade with karma:
I will bundle all my client's code & test cases separately into a single file. Example: client.js & test_cases.js.
I will have a separate file(say test.js)where I will declare some global which will be used for running my test cases . In this file, I will also invoke my client's code and test- cases using minispade.require().Here is how my test.js file will look:
mocha.setup({ ui: 'bdd', ignoreLeaks: true });
var assert = chai.assert; ........
window.minispade.require('app/main'); // Client's code
window.minispade.require("spec/main"); // Test cases
Here main.js refers to a file where I have included all my client &
test cases modules using minspade.require().
In karma configuration file, I will include test cases code under files. My configuration file will have the following lines:
files = [
{pattern : 'test_cases.js', included: true},
{pattern : test.js', included: true}
].
4 Run the karma run command.
Hope I have made myself clear. Do try it and let me know if you get stuck.