mirror of
https://github.com/microsoft/frontend-bootcamp.git
synced 2026-01-26 14:56:42 +08:00
adding bonus content for jest
This commit is contained in:
128
bonus-jest/demo/README.md
Normal file
128
bonus-jest/demo/README.md
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
# Bonus: Testing TypeScript code with Jest (Demo)
|
||||||
|
|
||||||
|
[Lessons](../) | [Exercise](./exercise/) | [Demo](./demo/)
|
||||||
|
|
||||||
|
[Jest](https://jestjs.io/) is a test framework made by Facebook and is very popular in the React and wider JS ecosystems.
|
||||||
|
|
||||||
|
In this exercise, we will work on implementing simple unit tests using Jest.
|
||||||
|
|
||||||
|
## Jest Features
|
||||||
|
|
||||||
|
- Multi-threaded and isolated test runner
|
||||||
|
- 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
|
||||||
|
|
||||||
|
- 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?
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// describe(), it() and expect() are globally exported, so they don't need to be imported when jest runs these tests
|
||||||
|
describe('Something to be tested', () => {
|
||||||
|
it('should describe the behavior', () => {
|
||||||
|
expect(true).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Testing React components using Enzyme
|
||||||
|
|
||||||
|
[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';
|
||||||
|
import { mount } from 'enzyme';
|
||||||
|
import { TestMe } from './TestMe';
|
||||||
|
|
||||||
|
describe('TestMe Component', () => {
|
||||||
|
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
|
||||||
|
|
||||||
|
### Mocking
|
||||||
|
|
||||||
|
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:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
it('some test function', () => {
|
||||||
|
const mockCallback = jest.fn(x => 42 + x);
|
||||||
|
mockCallback(1);
|
||||||
|
mockCallback(2);
|
||||||
|
expect(mockCallback).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Read more about jest mocking [here](https://jestjs.io/docs/en/mock-functions.html).
|
||||||
|
|
||||||
|
### Async Testing
|
||||||
|
|
||||||
|
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) => {
|
||||||
|
setTimeout(() => {
|
||||||
|
done();
|
||||||
|
}, 1000);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Returning a promise
|
||||||
|
it('tests promise functions', () => {
|
||||||
|
return someFunctionThatReturnsPromise());
|
||||||
|
});
|
||||||
|
|
||||||
|
// Async/await (recommended)
|
||||||
|
it('tests async functions', async () => {
|
||||||
|
expect(await someFunction()).toBe(5);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
# Demo
|
||||||
|
|
||||||
|
## Jest basics
|
||||||
|
|
||||||
|
In this repo, we can start an inner loop development of tests by running `npm test` from the root of the `frontend-bootcamp` folder.
|
||||||
|
|
||||||
|
Take a look at code inside `demo/src`:
|
||||||
|
|
||||||
|
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 when either test files or source files under `src` are saved.
|
||||||
15
bonus-jest/demo/index.html
Normal file
15
bonus-jest/demo/index.html
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<link rel="stylesheet" href="../../assets/step.css" />
|
||||||
|
</head>
|
||||||
|
<body class="ms-Fabric">
|
||||||
|
<div id="markdownReadme" data-src="./README.md"></div>
|
||||||
|
<div id="app">
|
||||||
|
For this step, we look at unit testing. Run
|
||||||
|
<pre>npm test</pre>
|
||||||
|
in the command line.
|
||||||
|
</div>
|
||||||
|
<script src="../../assets/scripts.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
11
bonus-jest/demo/src/TestMe.spec.tsx
Normal file
11
bonus-jest/demo/src/TestMe.spec.tsx
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { mount } from 'enzyme';
|
||||||
|
import { TestMe } from './TestMe';
|
||||||
|
|
||||||
|
describe('TestMe Component', () => {
|
||||||
|
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');
|
||||||
|
});
|
||||||
|
});
|
||||||
37
bonus-jest/demo/src/TestMe.tsx
Normal file
37
bonus-jest/demo/src/TestMe.tsx
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import React from 'react';
|
||||||
|
|
||||||
|
export interface TestMeProps {
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TestMeState {
|
||||||
|
clicked: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const TestMe = (props: TestMeProps) => {
|
||||||
|
return (
|
||||||
|
<div id="testMe">
|
||||||
|
<InnerMe name={props.name} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export class InnerMe extends React.Component<TestMeProps, TestMeState> {
|
||||||
|
state = {
|
||||||
|
clicked: false
|
||||||
|
};
|
||||||
|
|
||||||
|
onClick = () => {
|
||||||
|
this.setState({ clicked: true });
|
||||||
|
};
|
||||||
|
|
||||||
|
render() {
|
||||||
|
return !this.state.clicked ? (
|
||||||
|
<div onClick={this.onClick} id="innerMe">
|
||||||
|
Hello {this.props.name}, Click Me
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div id="innerMe">Clicked</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
7
bonus-jest/demo/src/index.spec.tsx
Normal file
7
bonus-jest/demo/src/index.spec.tsx
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { mount } from 'enzyme';
|
||||||
|
|
||||||
|
describe('index', () => {
|
||||||
|
it('placeholder', () => {
|
||||||
|
});
|
||||||
|
});
|
||||||
19
bonus-jest/demo/src/index.ts
Normal file
19
bonus-jest/demo/src/index.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { multiply } from './multiply';
|
||||||
|
|
||||||
|
let counter = 0;
|
||||||
|
|
||||||
|
export function getCount() {
|
||||||
|
return counter;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function increment() {
|
||||||
|
return ++counter;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decrement() {
|
||||||
|
return --counter;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function square(x: number) {
|
||||||
|
return multiply(x, x);
|
||||||
|
}
|
||||||
3
bonus-jest/demo/src/multiply.ts
Normal file
3
bonus-jest/demo/src/multiply.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export function multiply(x: number, y: number) {
|
||||||
|
return x * y;
|
||||||
|
}
|
||||||
17
bonus-jest/exercise/README.md
Normal file
17
bonus-jest/exercise/README.md
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
# Bonus: Testing TypeScript code with Jest (Exercise)
|
||||||
|
|
||||||
|
[Lessons](../) | [Exercise](./exercise/) | [Demo](./demo/)
|
||||||
|
|
||||||
|
Start the test runner by running `npm test` in the root of the `frontend-bootcamp` folder.
|
||||||
|
|
||||||
|
## Basic testing
|
||||||
|
|
||||||
|
1. Look at `exercise/src/stack.ts` for a sample implementation of a stack
|
||||||
|
|
||||||
|
2. Follow the instructions inside `stack.spec.ts` file to complete the two tests
|
||||||
|
|
||||||
|
## Enzyme Testing
|
||||||
|
|
||||||
|
1. Open up `exercise/src/TestMe.spec.tsx`
|
||||||
|
|
||||||
|
2. Fill in the test using Enzyme concepts introduced in the demo
|
||||||
15
bonus-jest/exercise/index.html
Normal file
15
bonus-jest/exercise/index.html
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<link rel="stylesheet" href="../../assets/step.css" />
|
||||||
|
</head>
|
||||||
|
<body class="ms-Fabric">
|
||||||
|
<div id="markdownReadme" class="exercise" data-src="./README.md"></div>
|
||||||
|
<div id="app">
|
||||||
|
For this step, we look at unit testing. Run
|
||||||
|
<pre>npm test</pre>
|
||||||
|
in the command line.
|
||||||
|
</div>
|
||||||
|
<script src="../../assets/scripts.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
13
bonus-jest/exercise/src/TestMe.spec.tsx
Normal file
13
bonus-jest/exercise/src/TestMe.spec.tsx
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { mount } from 'enzyme';
|
||||||
|
import { TestMe } from './TestMe';
|
||||||
|
|
||||||
|
describe('TestMe Component', () => {
|
||||||
|
it('should render correctly when hovered', () => {
|
||||||
|
// TODO:
|
||||||
|
// 1. mount a <TestMe> Component here
|
||||||
|
// 2. use enzyme wrapper's find() method to retrieve the #innerMe element
|
||||||
|
// 3. simulate a hover with "mouseover" event via the simulate() API
|
||||||
|
// 4. make assertions with expect on the text() of the #innerMe element
|
||||||
|
});
|
||||||
|
});
|
||||||
37
bonus-jest/exercise/src/TestMe.tsx
Normal file
37
bonus-jest/exercise/src/TestMe.tsx
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import React from 'react';
|
||||||
|
|
||||||
|
export interface TestMeProps {
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TestMeState {
|
||||||
|
enabled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const TestMe = (props: TestMeProps) => {
|
||||||
|
return (
|
||||||
|
<div id="testMe">
|
||||||
|
<InnerMe name={props.name} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export class InnerMe extends React.Component<TestMeProps, TestMeState> {
|
||||||
|
state = {
|
||||||
|
enabled: false
|
||||||
|
};
|
||||||
|
|
||||||
|
onMouseOver = () => {
|
||||||
|
this.setState({ enabled: true });
|
||||||
|
};
|
||||||
|
|
||||||
|
render() {
|
||||||
|
return !this.state.enabled ? (
|
||||||
|
<div onMouseOver={this.onMouseOver} id="innerMe">
|
||||||
|
Hello {this.props.name}, Hover Over Me
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div id="innerMe">Enabled</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
2
bonus-jest/exercise/src/index.ts
Normal file
2
bonus-jest/exercise/src/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { Stack } from './stack';
|
||||||
|
export { TestMe } from './TestMe';
|
||||||
18
bonus-jest/exercise/src/stack.spec.ts
Normal file
18
bonus-jest/exercise/src/stack.spec.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
// TODO: Import the stack here
|
||||||
|
|
||||||
|
describe('Stack', () => {
|
||||||
|
it('should push item to the top of the stack', () => {
|
||||||
|
// TODO: implement test here:
|
||||||
|
// 1. Instantiate a new Stack - i.e. const stack = new Stack<number>();
|
||||||
|
// 2. Use stack push calls to add some items to the stack
|
||||||
|
// 3. Write assertions via the expect() API
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should pop the item from the top of stack', () => {
|
||||||
|
// TODO: implement test here:
|
||||||
|
// 1. Instantiate a new Stack - i.e. const stack = new Stack<number>();
|
||||||
|
// 2. Use stack push calls to add some items to the stack
|
||||||
|
// 3. pop a few items off the stack
|
||||||
|
// 4. write assertions via the expect() API
|
||||||
|
});
|
||||||
|
});
|
||||||
27
bonus-jest/exercise/src/stack.ts
Normal file
27
bonus-jest/exercise/src/stack.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
export class Stack<T> {
|
||||||
|
private _items: T[] = [];
|
||||||
|
|
||||||
|
/** Add an item to the top of the stack. */
|
||||||
|
push(item: T) {
|
||||||
|
this._items.push(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remove the top item from the stack and return it. */
|
||||||
|
pop(): T {
|
||||||
|
if (this._items.length > 0) {
|
||||||
|
return this._items.pop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Return the top item from the stack without removing it. */
|
||||||
|
peek(): T {
|
||||||
|
if (this._items.length > 0) {
|
||||||
|
return this._items[this._items.length - 1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the number of items in the stack/ */
|
||||||
|
get count(): number {
|
||||||
|
return this._items.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -143,6 +143,14 @@
|
|||||||
Redux: Service Calls
|
Redux: Service Calls
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
|
<li class="Tile Tile--numbered">
|
||||||
|
<div class="Tile-link">
|
||||||
|
jest: testing code
|
||||||
|
<div class="Tile-links">
|
||||||
|
<a target="_blank" href="./bonus-jest/demo/">demo</a> | <a target="_blank" href="./bonus-jest/exercise/">exercise</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
<div class="Container">
|
<div class="Container">
|
||||||
|
|||||||
Reference in New Issue
Block a user