docs/react-v9/contributing/testing-with-jest.md
Fluent UI's unit, functional, and snapshot tests are built using Jest. This allows us to run tests in a Node environment but simulates the browser using jsdom.
We use various libraries on top of Jest for rendering and interacting with React components:
Old monorepo libraries (like v8)( none of these approaches is allowed in any new tests ):
From your Terminal invoke one of following commands:
yarn nx run <project-name>:test
New packages (v9) don't require build step before, which is not true for old fluent libraries like v8. Until v8 lives within our main branch we cannot remove
builddependency from target task graph thus you'll experience build step even for new packages.You can use
yarn workspace <package-name> testfor new packages if you don't have build within your cache and don't wanna wait forbuildstep
When you are developing tests, use the watch mode to run the tests as you write them!
yarn start-test, or for v9, yarn test --watchThe repo includes launch configurations for debugging tests using Visual Studio Code. (You could also configure debugging in another editor of your choice.)
*.test.ts,*.spec.ts,*.test.tsx,*.spec.tsx)expect matchersjest object including fake timer APIs (more info)Note that you do not need to import the assertions or the Jest APIs; they should be available automatically through the included typings.
A basic test example:
describe('thing', () => {
it('does something', () => {
expect(thing()).toEqual(aValue);
});
});
In cases where you need to automate a component and validate it performs correctly, you can use React Testing Library to mount components, evaluate DOM structure, and simulate events.
Here's a very basic example of what a test might look like (we'll go over this in more detail later):
const onClick = jest.fn();
const { getByRole } = render(<Button onClick={onClick}>This is a button</Button>);
userEvent.click(getByRole('button'));
expect(onClick).toHaveBeenCalled();