closing open handles detected by jest - javascript

i am writting tests for a node application which uses bull to process background jobs.
the test seems to be passing and working as expected but i am seeing the following error message
Jest has detected the following
8 open handles potentially keeping
Jest from exiting:
the log points to specifically this line and other similar statements.
const csvExportsQueue = ['test', 'development'].includes(process.env.NODE_ENV) ? new Queue('exports') : new Queue('csv exports', 'redis://redis:6379/13');
I tried to add the below statement to my test but it still gives the same error
afterAll(async () => {
await new Promise(resolve => setTimeout(() => resolve(), 10000)); // avoid jest open handle error
});
any help on how to fix this will be great, thanks.

add "jest --detectOpenHandles" to "test" in package.json to see the openhandles for Debugging
check your db connection (most likely) and close it them with connection.end()

Related

how to open node in a new terminal from cmd?

when I type start node into the cmd it starts up a new node terminal like this:
but how do I get it to run a script in the node terminal and close it after it's done?
maybe something like this?
start node "index.js" (when I try this it opens a terminal then immediately closes)
index.js:
console.log('hello there!');
await new Promise(r=>setTimeout(r,3000));
Top-level awaits aren't supported in Node versions prior to 14.18.0; there is a helpful discussion on GitHub as to why.
Since you're running v14.17.6, you'll need to wrap your code in an anonymous async function, then invoke it with ():
(async () => {
console.log('hello there!');
await new Promise(r=>setTimeout(r,3000));
})();
The resulting Node terminal will await for your timeout period before being closed.
(It may also behoove those reading this answer to ensure that they are correctly referencing the script they wish to execute relative to their command line's current working directory; see comment below by #cakelover.)

Pending operations in playwright on nodejs

I'm trying to get a new page at the moment of clicking on the link:
await test.step(`Step name`, async () => {
const [newPage] = await Promise.all([
context.waitForEvent('page'),
page.click('//span[normalize-space(#title)=\'Bup\']')
]);
}
And I get this page. Further operations with this instance are successful. But after 30 seconds the test ends with the following error:
Timeout of 30000ms exceeded.
Pending operations:
- browserContext.waitForEvent at "path to the file":48:21
- at <unknown>
I will assume that it is related to a promise, but I do not understand what exactly the problem is. Help is needed.
Playwright v14.0, nodejs v16.7.0.
I run the tests with the following command: npx playwright test tests/diag.spec.mjs --headed
A strange observation. When I run it in debug mode, there is no such error
:
PWDEBUG=1 npx playwright test tests/diag.spec.mjs
Ok, I found the answer, but it's a little weird. You need to increase the timeout in the playwright config:
https://github.com/microsoft/playwright/issues/8268
Also you can add test.slow() https://playwright.dev/docs/api/class-test#test-slow

Javascript promise never resolves

I am using rotateByDegrees from a library called node-poweredup in a typescript project:
motor.rotateByDegrees(20,10).then(function(value) {console.log("test");}, function(value) {console.log("error");});
I would expect to see "test" after successful completion, but the promise never resolves. If I use await, it hangs on the await line forever.
Replicating the syntax that appears to be used in the rotateByDegrees function:
let promise = new Promise((resolve) => { return resolve(); });
does not compile, I get error TS2794: Expected 1 arguments, but got 0. Did you forget to include 'void' in your type argument to 'Promise'? I can make it compile and behave as expected with resolve(true), but how does it compile in the library then? Do I misunderstand promises? Some feature in typescript? A bug in the library? I am a newbie to JavaScript, I don't want to over-complicate this question by including irrelevant details. If you can give me hints on what I am missing and how to debug this, I can provide all relevant details.
Thanks to the helpful comments I was able to narrow it down to the compilation of the library. I did in fact not use a pre-compiled binary but had to compile the library myself using electron-rebuild to make the bluetooth adapter work. I did the following test:
git clone https://github.com/nathankellenicki/node-poweredup.git
cd node-poweredup
npm install
npm run build
this compiles without error. I created the following test file
const PoweredUP = require("node-poweredup");
const poweredUP = new PoweredUP.PoweredUP();
poweredUP.scan(); // Start scanning for hubs
console.log("Looking for Hubs...");
poweredUP.on("discover", async (hub) => { // Wait to discover hubs
await hub.connect(); // Connect to hub
console.log(`Connected to ${hub.name}!`);
const motorA = await hub.waitForDeviceAtPort("A"); // Make sure a motor is plugged into port A
motorA.rotateByDegrees(20,10).then(function(value) {console.log("test");});
});
and get the expected output:
node-poweredup$ node test.js
Looking for Hubs...
Connected to MyHub2!
test
Connected to MyHub3!
test
When I changed the first line to
const PoweredUP = require(".");
to make it use my self-compiled binary I get
node-poweredup$ node test.js
Looking for Hubs...
Connected to MyHub2!
Connected to MyHub3!
Of course this is only a partial answer because I still don't know why it compiles differently on my machine, but at least I have an idea where to start searching for the problem.

Jest gives "Your test suite must contain at least one test" when certain file is imported even though there is a valid test

Whenever I import a certain file from my test file, Jest produces an error that I do not have any tests in the test file, even though there is one with just constants that should pass.
This is running inside a create-react-app folder, but I am using a global install of Jest for the server-side testing.
The Error
FAIL server/__tests__/server.test.js
● Test suite failed to run
Your test suite must contain at least one test.
at onResult (../../../../usr/lib/node_modules/jest/node_modules/#jest/core/build/TestScheduler.js:173:18)
A simplified version of the test file:
const timer = require("./timer.js");
test("should pass", () => {
expect(1 + 2).toBe(3);
});
A simplified version of timer.js:
class Timer {
constructor(ms, onCompleteFunction) {
this.ms = ms;
this.startTime = Date.now();
setTimeout(onCompleteFunction, ms);
}
}
test = () => {
let timer = new Timer(5000, () => console.log("Test Done!"));
};
test();
module.exports = Timer;
(This is a self-answer)
Before adding real testing with Jest, in the Timer.js file I had added a quick test function, just to verify that it was working without running the whole app.
Unfortunately, the function, named test, was not prefixed with var, let, or const. From what I can tell, it overrode the test function from the Jest library, and this error message was the result. When test = 1 or similar was present, the error was
TypeError: test is not a function
This is an extreme edge case due to poor coding practices and something I would have thought was a syntax error on my part, so I don't fault the error message for being unhelpful. I hope this can help someone in the future anyways.

Jest Call retries were exceeded

I have error in the following below test. My node version is : v12.10.0. is there any alternative of setTimeout?
test('demo code', async () => {
const cc = await projectSetup(project);
const onNotification = jest.fn();
cc.sendNotification();
await waitForExpect(() => {
expect(onNotification).toHaveBeenCalledTimes(2);
});
});
The Error log is as
Call retries were exceeded
at ChildProcessWorker.initialize (../../../node_modules/jest-worker/build/workers/ChildProcessWorker.js:230:21)
just add jest.useFakeTimers(); after your imports
...
jest.useFakeTimers();
test('demo code', async () => {
const cc = await projectSetup(project);
const onNotification = jest.fn();
cc.sendNotification();
await waitForExpect(() => {
expect(onNotification).toHaveBeenCalledTimes(2);
});
});
it works in my code
In my case, the actual problem was with the promise handling.
I got the same issue when I was running all my test cases in one go with the jest.
Solution:
Try running one test separately then see what error is coming.
I got the below error after running one problematic test separately where earlier I was getting the Call retries were exceeded:
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "TypeError: Cannot read property 'code' of undefined".] {
code: 'ERR_UNHANDLED_REJECTION'
}
With this, I was sure that the problem is with the catch block and when I added it in the async service API function then the test case worked perfectly fine.
Maybe you can also try the same and see if it works for you or not.
I am using the below config:
node: 15.13.0
npm: 7.8.0
jest: 26.6.3
Try running npm doctor using the latest npm version. It's a great tool and it helped me diagnose permission and ownership issues right away.
Takeaway:
Verify File/Folder Permissions & Ownership
Encountered same error when updating the vue-jest version to below listed versions
#vue/vue3-jest: ^27.0.0-alpha.4
#vue/cli-plugin-unit-jest: ~5.0.0,
node: v17.9.0 or v16.14.2
Error disappeared, once downgraded it to node version v14.x.x
Hunch is - the latest node versions are not compatible with the dependencies.
I was able to run the test's successfully doing the following;
Install npm i -D jest-canvas-mock
Update the jest.config.ts file to have:
export default {
...
testEnvironment: "jsdom",
setupFiles: ["jest-canvas-mock"],
}

Categories