0

I am trying to test an async function that fetches data from a json file and stores it in a variable

The function I am trying to test (present in registration.js):

async function readJSONFile(url) {
    const data = await $.getJSON(url);
    return data;
}

let returnedData = await readJSONFile(testURL);

module.exports = readJSONFile;

How can I create a test file using jest in order to test this function?

I tried this code for testing but for some reason, it is not reading the main javascript file

const readJSONFile = require("../JS/registration.js").readJSONFile;


test("check if the data is retrieved", async () => {
    const testData = {
        "courseName" : {
            "instrName" : "profName",
            "location" : "classLocation",
            "timings" : "classTimings"
        }
    }

    const data = await  $.getJSON(testURL);
    expect(data).toBe(testData)
});

The error:

SyntaxError: await is only valid in async functions and the top level bodies of modules

Project Structure:

| Jest Testing
    | registration.test.js

| JS
    | registration.js

1 Answer 1

0

require expects a module path and returns the exports object.

You've appended the property name to the path.

You've also failed to account for the two JS files being in different directories.

const readJSONFile = require("../JS/registration.js").readJSONFile;
1
  • I have updated the code but got a new error
    – prav
    Commented Apr 8, 2023 at 22:09

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.