Deno-test encounters an undetermined AssertionError

Below is a test case example for Deno that I am using:

Deno.test("Run LS", () => {
  const cmd = Deno.run({
    cmd: ["ls"],
    stdout: "piped",
    stderr: "piped",
  });

  let status: Deno.ProcessStatus, stdout: string, stderr: string;

  const f = async () => {
    const [status_, stdout_, stderr_] = await Promise.all([
      cmd.status(),
      cmd.output(),
      cmd.stderrOutput(),
    ]);
    cmd.close();

    status = status_;
    stdout = new TextDecoder().decode(stdout_);
    stderr = new TextDecoder().decode(stderr_);
  };

  f()
    .then(
      function (result) {
        console.log(`My result: ${result}`);

        console.log(`status: `, status);
        console.log(`stdout: `, stdout);
        console.log(`stderr: `, stderr);

      },
      function (error) {
        console.log(`My error: ${error}`);
      }
    )
    .catch(function (error) {
      console.log(`My cought error: ${error}`);
    })
    .finally(function () {
      console.log("In the finally clause...");
    });
});

When running the test using

deno test --allow-read --allow-run --unstable <filename>
, sometimes the output is as follows:

running 1 tests
test fetch pending tasks ... My result: undefined
status:  { success: true, code: 0 }
stdout:  a.ts
<rest of files in the directory>

stderr:
In the finally clause...
ok (7ms)

Other times, an assertion error occurs:

running 1 tests
test Run LS ... FAILED (4ms)

failures:

Run LS
AssertionError: Test case is leaking async ops.
Before:
  - dispatched: 0
  - completed: 0
After:
  - dispatched: 5
  - completed: 4

Make sure to await all promises returned from Deno APIs before
finishing test case.
    at assert (deno:runtime/js/06_util.js:34:13)
    at asyncOpSanitizer (deno:runtime/js/40_testing.js:50:7)
    at async resourceSanitizer (deno:runtime/js/40_testing.js:74:7)
    at async Object.exitSanitizer [as fn] (deno:runtime/js/40_testing.js:101:9)
    at async TestRunner.[Symbol.asyncIterator] (deno:runtime/js/40_testing.js:275:13)
    at async Object.runTests (deno:runtime/js/40_testing.js:352:22)
    at async file:///home/berger/src/taskwarrior-deno/$deno$test.ts:3:1

failures:

        Run LS

If I run the function as a regular script instead of using Deno.test(), the assertion error does not occur.

Is this the correct way to use Deno.run? If so, please advise if there are any issues with my implementation or if it is deno itself causing the problem.

I'm new to JavaScript, so any additional tips on improving the code are welcome.

Answer №1

After raising the same question on a Deno GitHub issue, I received the following solution:

Check it out here: https://github.com/denoland/deno/issues/9767#issuecomment-797466192

Deno.test("Execute LS Command", async () => {
  const cmd = Deno.run({
    cmd: ["ls"],
    stdout: "piped",
    stderr: "piped",
  });
  const fetchData = async () => {
    const [status_, stdout_, stderr_] = await Promise.all([
      cmd.status(),
      cmd.output(),
      cmd.stderrOutput(),
    ]);
    cmd.close();

    return {
      status: status_,
      stdout: new TextDecoder().decode(stdout_),
      stderr: new TextDecoder().decode(stderr_),
    };
  };
  try {
    const { status, stderr, stdout } = await fetchData();
    console.log("Status:", status);
    console.log("Standard Output:", stdout);
    console.log("Standard Error:", stderr);
  } catch (error) {
    console.log("Error Encountered:", error);
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

submit a JSON object using a form in C# MVC

I'm attempting to transmit a JSON serialized object via a form to a C# MVC action. var obj = { id: 1, field1: "", field2: "", . . . } var inputs = "<input type'hidden' name='serializedObject' value='" + JSON.s ...

Error: When attempting to read the 'useState' property on the Next.js Page Router, a TypeError occurs due to null values. This issue is specific to the Next.js Page Router

Currently, I am in the process of developing a straightforward useState React hook library utilizing the tsup bundler. I wanted to showcase the usage examples with both NextJs App Router and Page Router. The library functions perfectly within the App Route ...

Encountering a syntax error while transferring information from Ajax to PHP

I am currently experiencing an issue with my Ajax and PHP setup. Upon checking the browser console, I encountered the following error message: The following error occured: parsererror SyntaxError: Unexpected token <. Despite multiple attempts at debugg ...

Once the print dialog is canceled or saved, the current window remains open

Whenever I try to print the data, a new window opens displaying all the respective data of the HTML page. The print dialog then quickly appears, but if I cancel or close the dialog, the current window does not close. Can someone please provide suggestions ...

The unspoken rules of exporting and importing in TypeScript

In comparison to Java (as well as other programming languages), TypeScript provides multiple options for exporting and importing entities such as classes, functions, etc. For instance, you have the ability to export numerous classes, constants, functions ...

The function Func<T extends IComponent>( ) returns an array of type T that extends IComponent, which ultimately results in an array of IComponent[] without explicitly assigning

Currently, I am attempting to implement the ECS pattern in TypeScript. I have created a class called ComponentStore that contains components of entities for future handling purposes. Here is an example of what these components look like: class Health impl ...

Converting a standard redux object into a format suitable for display

Working on a React Native project with Redux, I need guidance on transforming data for rendering purposes. The data structure I have is a normalized object called userDetails, which looks like this: "userDetails": Object { "allIds": ...

Failed to load CSS file in nodeJS application

I followed a tutorial to create a backend app using nodeJS and Express. My MongoDB connection with Mongoose is working fine. However, I am facing issues when trying to add a simple front-end using html/ejs/css. The endpoints are loading on localhost but on ...

Error: The property 'create' of undefined cannot be read (Material UI/enzyme)

When I mount a component, I encounter an error that does not occur when using shallow rendering. The specific error is: TypeError: Cannot read property 'create' of undefined at stylesOrCreator (node_modules/@material-ui/core/CircularProgress/C ...

Clicking 'Back to Top' within an accordion

On my webpage, I have two scrolls present. One is clearly visible on the page (not loaded with ajax), while the other one is located inside an accordion. Both of them share the same class names. I want these scrolls to always be positioned at the top. I&a ...

Show image in ReactJS using flask send_file method

Using Flask's send_file function, I send an image to the client in the following way: @app.route('/get-cut-image',methods=["GET"]) def get_cut_img(): response = make_response(send_file(file_path,mimetype='image/png')) respon ...

Make sure to always keep all stars contained within a div element

How can I keep five stars inside a div even when the screen size is small? I have created a div with an image and I want to place five stars within that div. However, as I reduce the size of the screen, the stars come out of the box. Is there a way to en ...

Feeling lost on how to utilize .map, .reduce, or foreach in my code

Recently delving into JavaScript, I find myself a bit perplexed despite scouring through various answers and resources on Mozilla.org. My struggle lies in seamlessly using .map and .filter on straightforward arrays, but feeling a bit lost when it comes to ...

What is the proper way to document JSDoc in JavaScript specifically for the TypeScript Compiler?

There is a feature that allows you to check JS code with the TS compiler. The TS compiler also recognizes JSDoc comments (https://github.com/Microsoft/TypeScript/wiki/JSDoc-support-in-JavaScript). I am looking to utilize the TS compiler in my React projec ...

The beauty of asynchronous GET requests in VueJS

As a newcomer to VueJS, I am exploring how to make a GET request to the GitHub API. Initially, I made a request to sort users by follower count, resulting in an array ordered in descending order of user logins. Following that, I sent another GET request to ...

Tips for aligning the dropdown menu to start from the border of the menu bar instead of displaying directly below the text

I have designed a menu-header section for my website, inspired by this image. I created a fiddle to showcase it. However, I am facing an issue where the dropdown elements for "PROGRAMS" and "WORLD OF NORTHMAN" should start from the border of the header ins ...

Implementing universal design in Next.js 14

I'm encountering a problem while trying to use the style jsx global property in the latest version of Next.js. Previously, you would include it in the _app.js file, but since that file no longer exists, I assumed it should be added to the layout.tsx f ...

I am experiencing an issue with my Angular directive where the button click does not

Check out this page for guidance on adding a div with a button click in AngularJS: How to add div with a button click in angularJs I attempted to create an angular directive that should add a div to my HTML page when a button is clicked. However, upon cli ...

Issue with custom cursor not functioning properly when hovering over hyperlinks

I'm currently developing a website and I've created a custom cursor to replace the default one. The custom cursor is detecting mouse movement, but it's not interacting with hyperlinks. Below is the code I'm using. HTML <div class=& ...

Tips for Identifying Different ID Values of HTML Elements with jQuery

Currently, I have two different divs on my webpage, each containing buttons and hidden fields. When I try to pass the value of the hidden field attached to the button in a jQuery function, I encounter an issue where clicking on the second div results in pa ...