Testing Projects

This chapter will describe how to test modules.

Prerequisites and conventions

To use the testing features of the project, you need to make sure that the project contains the dependency: "@modern-js/plugin-testing" , which can be done with modern new.

In Modern.js Module, the following conventions are in place for test cases, or files for writing tests:

  • The tests directory in the project directory is the directory for test cases and test files, no support for changing the directory for running test cases.
  • Files with the suffix .test.[tj]sx? are automatically recognized as test files by default.
  • Other . [tj]sx? suffixes are recognized as normal files that can be used as test utils files or for other purposes.

Run the tests

Once the dependencies are prepared and we know where to write the test cases, we can execute the tests with the following command:

modern test

// Update snapshot
modern test --updateSnapshot

After execution, you will see the results of the test:

test-result

Usage Configuration

Modern.js Module provides the following configurations for testing.

You can add it in modern.config.(j|t)s.

Test example

Common modules

For common modules, we can use the test function as follows:

  • First is the code of the module:
./src/index.ts
export default function () {
  return 'hello world';
}
  • Then in the test file, we can import source code as the following way. Where @ points to the source directory, defined in tests/tsconfig.json in the initialization project.
./tests/index.test.ts
import main from '@/index';

describe('default cases', () => {
  test('Have returns', () => {
    const drink = jest.fn(main);
    drink();
    expect(drink).toHaveReturned();
  });
});
  • Finally we can execute modern test.
pnpm test
## or
yarn test
## or
npm run test

Components

For components, Modern.js's Runtime API provides functionality for testing UI components, which is provided by @modern-js/runtime/testing.

TIP

If you need to use the Runtime API, then you can turn it on via microgenerator.

  • First is the code of the component:
./src/index.tsx
export default () => {
  return <div>This is a UI Component</div>;
};
  • Then in the test file, we can import source code as the following way. Where @ points to the source directory, defined in tests/tsconfig.json in the initialization project.
./tests/index.test.tsx
import { render, screen } from '@modern-js/runtime/testing';

import Component from '@/index';

describe('default cases', () => {
  test('Rendered', () => {
    render(<Component />);
    expect(screen.getByText('This is a UI Component')).toBeInTheDocument();
  });
});
  • Finally we can execute modern test.
pnpm test
## or
yarn test
## or
npm run test