Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: write tests and refactor scripts #3012

Merged
merged 20 commits into from
Jul 1, 2024

Conversation

vishvamsinh28
Copy link
Contributor

This PR sets up Jest for testing Node.js scripts, refactors few existing scripts for better readability and maintainability, and adds initial tests to ensure functionality. It also includes coverage reporting setup and updates .gitignore to exclude coverage files.

Copy link

netlify bot commented May 31, 2024

Deploy Preview for asyncapi-website ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 02faf33
🔍 Latest deploy log https://app.netlify.com/sites/asyncapi-website/deploys/6682b4d757e6b10008980fb5
😎 Deploy Preview https://deploy-preview-3012--asyncapi-website.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@asyncapi-bot
Copy link
Contributor

asyncapi-bot commented May 31, 2024

⚡️ Lighthouse report for the changes in this PR:

Category Score
🔴 Performance 46
🟢 Accessibility 98
🟢 Best practices 92
🟢 SEO 100
🟠 PWA 56

Lighthouse ran on https://deploy-preview-3012--asyncapi-website.netlify.app/


await writeFile(writePAth,JSON.stringify(jsonContent));
}catch(error){
console.log(error)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use console.error for error logging. Update the related tests.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


describe('convertToJson', () => {
test('should return JSON object if input is valid JSON string', () => {
const jsonString = '{"name": "AsyncAPI", "age": 5}';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you create an actual json file (for tests only), and read its content on the go rather than hard-coding JSON strings like this?

If fs module isn't working in jest, you can even create js objects and use json.stringify() to convert objects to JSON String.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can create fixtures to store the static data that are needed in tests.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

});

test('should return JavaScript object if input is valid YAML string', () => {
const yamlString = 'name: AsyncAPI\nage: 5';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Try to read actual yaml file here, and iff its not viable, use multiline string. Example:

    const yamlString = `
      name: AsyncAPI
      age: 5
    `

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


test('should return null if input is invalid JSON and invalid YAML', () => {
const invalidString = 'name: AsyncAPI, age: five';
const result = convertToJson(invalidString);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enclose it in a try catch statement, and add an expect statement for verifying the error.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

test('should read a file, convert it to JSON, and write the JSON to another file', async () => {
const readPath = 'config/testInput.yaml';
const writePath = 'config/testOutput.json';
const fileContent = 'name: AsyncAPI\nage: 5';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use multiline strings for better readability.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment on lines 37 to 48
test('should log an error if reading the file fails', async () => {
const readPath = 'config/testInput.yaml';
const writePath = 'config/testOutput.json';
const error = new Error('File read error');

fs.readFile.mockRejectedValue(error);
console.log = jest.fn();

await writeJSON(readPath, writePath);

expect(console.log).toHaveBeenCalledWith(error);
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Try using try catch block to catch error instead of mocking console.log

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment on lines 5 to 11
try{
const readContent = await readFile(readPath,'utf-8');
const jsonContent = convertToJson(readContent);

await writeFile(writePAth,JSON.stringify(jsonContent));
}catch(error){
console.log(error)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of catching the error for all three operations, you can use nested try catch or different try catch scopes to better write tests that would allow you know which out of these three operations (readFile, convertToJson, writeFile) has failed.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

@anshgoyalevil
Copy link
Member

In the coverage report, there need to be other scripts as well, so that we can track which script has left, i.e., has 0 coverage.
If I am correct, There is a jest configuration to define the folder to track coverage for. Try adding that

Copy link
Member

@akshatnema akshatnema left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see that you are using console.log statements inside test to assert the values. Instead, you can refactor the functions in such a way that they return some response based on execution, and you can then test their functionalities.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make a util directory inside scripts and add these functions inside this folder. Also change the filename to a relevant one.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


describe('convertToJson', () => {
test('should return JSON object if input is valid JSON string', () => {
const jsonString = '{"name": "AsyncAPI", "age": 5}';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can create fixtures to store the static data that are needed in tests.

@anshgoyalevil
Copy link
Member

@vishvamsinh28 Any updates on this PR?

@vishvamsinh28
Copy link
Contributor Author

@anshgoyalevil updated the tests

try {
expect(convertToJson(jsonString)).toEqual(jsonObject);
} catch (err) {
console.error(err);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add throw statements here also

tests/utils.test.js Outdated Show resolved Hide resolved
@asyncapi-bot asyncapi-bot requested a review from TRohit20 June 16, 2024 04:54
@anshgoyalevil
Copy link
Member

anshgoyalevil commented Jun 16, 2024

@vishvamsinh28 I have updated the utils.test.js. You can watch out for where exactly the expect statements for test cases related to errors should go.

And, for test cases which are not supposed to fail, they shouldn't ideally be enclosed in a try catch block since the function being tested upon there is already enclosed in a try catch block, which is sufficient to throw an error and fail that specific test case.

For example,

In

test('should return JSON object if input is valid JSON string', () => {
    expect(convertToJson(jsonString)).toEqual(jsonObject);
  });

The convertToJson already contains a try catch block with throw new Error statement. Now, suppose, the function fails to parse the jsonString, the above test case would fail (and it should fail, that what tests are supposed to do) since an error would be thrown in convertToJson.

Update other tests whereever applicable, and make sure there is a throw new Error statement along with console.error statement in the scripts. Similarly, make sure there is no console.error or throw new Error statement inside the tests.

Another thing is the prettier. Don't know why .js files are getting formatted automatically with npm run lint:fix. Maybe a configuration error on eslint side.
For now, you make sure the files changed in this PR are formatted. (Tip: I just press ctrl+s inside a specific file in vscode, and it gets formatted, maybe due to prettier extension?)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you have a different filename here as per camelCase naming convention and a more meaningful one?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes will update it

Comment on lines 8 to 10
beforeEach(() => {
jest.clearAllMocks();
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it required here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not really but good to have if we add more tests to it

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it will be needed, we'll add it in the future. For now, you can remove it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay 👍

const error = new Error('File read error');

fs.readFile.mockRejectedValue(error);
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need to mockImplementation for console.error function?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to prevent the output to log in the console during tests. If we log errors to the console that can clutter the output and make it harder to identify test failures when we have multiple tests

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think there will be any problem with console error messages. You shouldn't mock this implementation as it will help us to detect the flow of the function, on a desired test.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay 👍 I'll update it

`Error reading file from path ${readPath}:`,
error
);
consoleErrorSpy.mockRestore();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need this as we already cleared the mocks in beforeEach callback?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes we already have it in beforeEach and it works well even if i remove it but clearAllMocks does not restore it to its original implementations so i added it


test('should throw an error if input is invalid JSON and invalid YAML', () => {
try {
convertToJson(invalidString);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also check that there shouldn't be any value returned from the function.

tests/write-json.test.js Outdated Show resolved Hide resolved
@vishvamsinh28
Copy link
Contributor Author

vishvamsinh28 commented Jun 18, 2024

I have updated the tests for throwing errors correctly i 2 have implementations for it which one should push changes for ?
Screenshot 2024-06-18 at 11 36 13 AM

Screenshot 2024-06-18 at 11 36 38 AM

i have updated script as well
Screenshot 2024-06-18 at 11 39 54 AM

and i have removed console.error from the script

@anshgoyalevil @sambhavgupta0705 @akshatnema

@vishvamsinh28
Copy link
Contributor Author

vishvamsinh28 commented Jun 18, 2024

Another thing is the prettier. Don't know why .js files are getting formatted automatically with npm run lint:fix. Maybe a configuration error on eslint side. For now, you make sure the files changed in this PR are formatted. (Tip: I just press ctrl+s inside a specific file in vscode, and it gets formatted, maybe due to prettier extension?)

i just removed prettier when we added it back to the project because it was giving me a lot of lint/prettier errors 😅
@anshgoyalevil

anshgoyalevil
anshgoyalevil previously approved these changes Jun 20, 2024
@anshgoyalevil
Copy link
Member

@vishvamsinh28 Kindly update PR title, and resolve merge conflicts

@vishvamsinh28 vishvamsinh28 changed the title feat: add jest to the project and refactor scripts feat: write tests and refactor scripts Jul 1, 2024
akshatnema
akshatnema previously approved these changes Jul 1, 2024
@anshgoyalevil
Copy link
Member

Merging since it already got Akshat's approval 🚢

@anshgoyalevil
Copy link
Member

/rtm

@asyncapi-bot asyncapi-bot merged commit 09d1652 into asyncapi:master Jul 1, 2024
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
gsoc This label should be used for issues or discussions related to ideas for Google Summer of Code ready-to-merge
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants