mirror of
https://github.com/microsoft/frontend-bootcamp.git
synced 2026-01-26 14:56:42 +08:00
Steps 2-3 and 2-4
This commit is contained in:
@@ -1,28 +1,27 @@
|
||||
# Step 2.4
|
||||
# Step 2.4: Testing TypeScript code with Jest
|
||||
|
||||
[Lessons](../) | [Exercise](./exercise/) | [Demo](./demo/)
|
||||
|
||||
Testing TypeScript code with jest. jest is a test framework made by Facebook and is very popular in the React and the wider JS ecosystem. We will work on implementing simple unit tests here in this exercise.
|
||||
[Jest](https://jestjs.io/) is a test framework made by Facebook and is very popular in the React and wider JS ecosystems.
|
||||
|
||||
https://jestjs.io/
|
||||
In this exercise, we will work on implementing simple unit tests using Jest.
|
||||
|
||||
# jest Features
|
||||
## Jest Features
|
||||
|
||||
- Multi-threaded and isolated test runner
|
||||
- Provides a "fake" browser environment if needed (window, document, DOM, etc).
|
||||
- Snapshots: show API or large object changes along side code changes in pull requests
|
||||
- Code coverage is integrated (--coverage)
|
||||
- Very clear error messages of where the test failures occur
|
||||
- By default, will simulate a "good enough" browser environment called JSDOM
|
||||
- Provides a fake browser-like environment if needed (window, document, DOM, etc) using jsdom
|
||||
- Snapshots: Jest can create text-based snapshots of rendered components. These snapshots can be checked in and show API or large object changes alongside code changes in pull requests.
|
||||
- Code coverage is integrated (`--coverage`)
|
||||
- Very clear error messages showing where a test failure occurred
|
||||
|
||||
# How to use jest
|
||||
## How to use Jest
|
||||
|
||||
- using `create-react-app` or other project generators, jest should already be preconfigured. Run `npm test` usually will trigger it!
|
||||
- needs `jest.config.js`
|
||||
- Using `create-react-app` or other project generators, Jest should already be pre-configured. Running `npm test` usually will trigger it!
|
||||
- A `jest.config.js` file is used for configuration
|
||||
- `jsdom` might not have enough API from real browsers, for those cases, polyfills are required. Place these inside `jest.setup.js` and hook up the setup file in `jest.config.js`
|
||||
- in order to use `enzyme` library to test React Components, more config bits are needed inside `jest.setup.js`
|
||||
|
||||
# What does a test look like?
|
||||
## What does a test look like?
|
||||
|
||||
```ts
|
||||
// describe(), it() and expect() are globally exported, so they don't need to be imported when jest runs these tests
|
||||
@@ -33,11 +32,15 @@ describe('Something to be tested', () => {
|
||||
});
|
||||
```
|
||||
|
||||
# Test React Components by using `enzyme`
|
||||
## Testing React components using Enzyme
|
||||
|
||||
- use `enzyme` to `mount()` the component (as oppose to rendering)
|
||||
- the `mount()` function will return a wrapper that can be inspected
|
||||
- the wrapper has functionality like `find()`, simulating clicks, etc.
|
||||
[Enzyme](https://airbnb.io/enzyme/) is made by Airbnb and provides utilities to help test React components.
|
||||
|
||||
In a real app using ReactDOM, the top-level component will be rendered on the page using `ReactDOM.render()`. Enzyme provides a lighter-weight `mount()` function which is usually adequate for testing purposes.
|
||||
|
||||
`mount()` returns a wrapper that can be inspected and provides functionality like `find()`, simulating clicks, etc.
|
||||
|
||||
The following code demonstrates how Enzyme can be used to help test React components.
|
||||
|
||||
```tsx
|
||||
import React from 'react';
|
||||
@@ -45,19 +48,32 @@ import { mount } from 'enzyme';
|
||||
import { TestMe } from './TestMe';
|
||||
|
||||
describe('TestMe Component', () => {
|
||||
it('should have a non-clickable component when the origina InnerMe is clicked', () => {
|
||||
it('should have a non-clickable component when the original InnerMe is clicked', () => {
|
||||
const wrapper = mount(<TestMe name="world" />);
|
||||
wrapper.find('#innerMe').simulate('click');
|
||||
expect(wrapper.find('#innerMe').text()).toBe('Clicked');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Foo Component Tests', () => {
|
||||
it('allows us to set props', () => {
|
||||
const wrapper = mount(<Foo bar="baz" />);
|
||||
expect(wrapper.props().bar).toBe('baz');
|
||||
wrapper.setProps({ bar: 'foo' });
|
||||
expect(wrapper.props().bar).toBe('foo');
|
||||
|
||||
wrapper.find('button').simulate('click');
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
# Advanced Topics
|
||||
## Advanced topics
|
||||
|
||||
## Mocking
|
||||
### Mocking
|
||||
|
||||
Mocking functions is a large part of what makes `jest` a powerful testing library. `jest` actually intercepts module inclusion process in `node.js` allowing it to mock entire modules if needed. There are many ways to mock as you can imagine in a language as flexible as JS. We only look at the simplest case but there's a lot of depth here.
|
||||
Mocking functions is a large part of what makes Jest a powerful testing library. Jest actually intercepts the module loading process in Node.js, allowing it to mock entire modules if needed.
|
||||
|
||||
There are many ways to mock, as you'd imagine in a language as flexible as JS. We only look at the simplest case, but there's a lot of depth here.
|
||||
|
||||
To mock a function:
|
||||
|
||||
@@ -66,33 +82,30 @@ it('some test function', () => {
|
||||
const mockCallback = jest.fn(x => 42 + x);
|
||||
mockCallback(1);
|
||||
mockCallback(2);
|
||||
expect(mockCallback.mock.calls.length).toBe(2);
|
||||
expect(mockCallback).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
```
|
||||
|
||||
Read more about jest mocking here: https://jestjs.io/docs/en/mock-functions.html
|
||||
Read more about jest mocking [here](https://jestjs.io/docs/en/mock-functions.html).
|
||||
|
||||
## Async Testing
|
||||
### Async Testing
|
||||
|
||||
### callback
|
||||
For testing async scenarios, the test runner needs some way to know when the scenario is finished. Jest tests can handle async scenarios using callbacks, promises, or async/await.
|
||||
|
||||
```ts
|
||||
// Callback
|
||||
it('tests callback functions', (done) => {
|
||||
someFunctionThatCallsDone(done));
|
||||
})
|
||||
```
|
||||
setTimeout(() => {
|
||||
done();
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
### promise
|
||||
|
||||
```ts
|
||||
// Returning a promise
|
||||
it('tests promise functions', () => {
|
||||
return someFunctionThatReturnsPromise());
|
||||
})
|
||||
```
|
||||
});
|
||||
|
||||
### (recommended) async / await
|
||||
|
||||
```ts
|
||||
// Async/await (recommended)
|
||||
it('tests async functions', async () => {
|
||||
expect(await someFunction()).toBe(5);
|
||||
});
|
||||
@@ -100,50 +113,29 @@ it('tests async functions', async () => {
|
||||
|
||||
# Demo
|
||||
|
||||
## jest basics
|
||||
## Jest basics
|
||||
|
||||
In this repo, we can start an inner loop development of tests with the command: `npm test`
|
||||
|
||||
Take a look at code inside `demo/src`:
|
||||
|
||||
1. `index.ts` is exports a few functions for a counter as well as a test for squaring numbers but demonstrates out jest uses mocks
|
||||
1. `index.ts` exports a few functions for a counter as well as a function for squaring numbers. We'll use this last function to demonstrate how mocks work.
|
||||
|
||||
2. `multiply.ts` is a contrived example of a function that is exported
|
||||
|
||||
3. `index.spec.ts` is the test file: note how tests are re-run on save to test file changes as well as source code changes under `src`
|
||||
3. `index.spec.ts` is the test file
|
||||
|
||||
## testing React applications
|
||||
|
||||
You can also test React Components with `jest` with the help of a partner library called `enzyme`. Take a look at the test below:
|
||||
|
||||
```ts
|
||||
import { mount } from 'enzyme';
|
||||
|
||||
describe('Foo Component Tests', () => {
|
||||
it('allows us to set props', () => {
|
||||
const wrapper = mount(<Foo bar="baz" />);
|
||||
expect(wrapper.props().bar).toBe('baz');
|
||||
wrapper.setProps({ bar: 'foo' });
|
||||
expect(wrapper.props().bar).toBe('foo');
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
`mount` does a full mount of the component. You can use the `enzyme` wrapper to simulate clicks, etc.:
|
||||
|
||||
```ts
|
||||
wrapper.find('button').simulate('click');
|
||||
```
|
||||
Note how tests are re-run when either test files or source files under `src` are saved.
|
||||
|
||||
# Exercise
|
||||
|
||||
## Basic Testing
|
||||
## Basic testing
|
||||
|
||||
1. Run the tests by running `npm test` at the root of the bootcamp project
|
||||
|
||||
2. Look at the `stack.ts` for a sample implementation of a stack
|
||||
2. Look at `exercise/src/stack.ts` for a sample implementation of a stack
|
||||
|
||||
3. Follow the instructions inside the `stack.spec.ts` file to complete the two tests
|
||||
3. Follow the instructions inside `stack.spec.ts` file to complete the two tests
|
||||
|
||||
## Enzyme Testing
|
||||
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import React from 'react';
|
||||
import { mount } from 'enzyme';
|
||||
import { TestMe } from './TestMe';
|
||||
|
||||
describe('TestMe Component', () => {
|
||||
it('should have a non-clickable component when the origina InnerMe is clicked', () => {
|
||||
const wrapper = mount(<TestMe name="world" />);
|
||||
wrapper.find('#innerMe').simulate('click');
|
||||
expect(wrapper.find('#innerMe').text()).toBe('Clicked');
|
||||
describe('index', () => {
|
||||
it('placeholder', () => {
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@ import { mount } from 'enzyme';
|
||||
import { TestMe } from './TestMe';
|
||||
|
||||
describe('TestMe Component', () => {
|
||||
it('should have a non-clickable component when the origina InnerMe is clicked', () => {
|
||||
it('should have a non-clickable component when the original InnerMe is clicked', () => {
|
||||
const wrapper = mount(<TestMe name="world" />);
|
||||
wrapper.find('#innerMe').simulate('click');
|
||||
expect(wrapper.find('#innerMe').text()).toBe('Clicked');
|
||||
|
||||
Reference in New Issue
Block a user