├── public
├── favicon.ico
├── manifest.json
└── index.html
├── src
├── feedbackMachine.js
├── App.e2e.js
├── App.test.js
├── index.css
├── index.js
├── App.css
├── logo.svg
├── App.js
└── serviceWorker.js
├── jest.config.js
├── jest-puppeteer.config.js
├── package.json
├── LICENSE
├── .gitignore
└── README.md
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davidkpiano/mbt-workshop/HEAD/public/favicon.ico
--------------------------------------------------------------------------------
/src/feedbackMachine.js:
--------------------------------------------------------------------------------
1 | import { Machine } from 'xstate';
2 |
3 | // Write your machine here
4 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | preset: 'jest-puppeteer',
3 | testRegex: './*\\.e2e\\.js$'
4 | };
5 |
--------------------------------------------------------------------------------
/src/App.e2e.js:
--------------------------------------------------------------------------------
1 | const { Machine } = require('xstate');
2 | const { createModel } = require('@xstate/test');
3 |
4 | // Write your E2E tests here
5 |
--------------------------------------------------------------------------------
/jest-puppeteer.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | server: {
3 | command: `npm start`,
4 | port: 3000,
5 | launchTimeout: 5000
6 | },
7 | launch: {
8 | headless: false,
9 | slowMo: 50
10 | }
11 | };
12 |
--------------------------------------------------------------------------------
/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import Feedback from './App';
3 | import { Machine } from 'xstate';
4 | import { render, fireEvent, cleanup } from '@testing-library/react';
5 | import { assert } from 'chai';
6 | import { createModel } from '../../xstate/packages/xstate-test/lib';
7 |
8 | // Write your integration tests here
9 |
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | }
10 | ],
11 | "start_url": ".",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | padding: 0;
4 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
5 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
6 | sans-serif;
7 | -webkit-font-smoothing: antialiased;
8 | -moz-osx-font-smoothing: grayscale;
9 | font-size: 24px;
10 | }
11 |
12 | code {
13 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
14 | monospace;
15 | }
16 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import App from './App';
5 | import * as serviceWorker from './serviceWorker';
6 |
7 | ReactDOM.render(, document.getElementById('root'));
8 |
9 | // If you want your app to work offline and load faster, you can change
10 | // unregister() to register() below. Note this comes with some pitfalls.
11 | // Learn more about service workers: http://bit.ly/CRA-PWA
12 | serviceWorker.unregister();
13 |
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | animation: App-logo-spin infinite 20s linear;
7 | height: 40vmin;
8 | }
9 |
10 | .App-header {
11 | background-color: #282c34;
12 | min-height: 100vh;
13 | display: flex;
14 | flex-direction: column;
15 | align-items: center;
16 | justify-content: center;
17 | font-size: calc(10px + 2vmin);
18 | color: white;
19 | }
20 |
21 | .App-link {
22 | color: #61dafb;
23 | }
24 |
25 | @keyframes App-logo-spin {
26 | from {
27 | transform: rotate(0deg);
28 | }
29 | to {
30 | transform: rotate(360deg);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "feedback",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@xstate/graph": "0.0.1",
7 | "@xstate/react": "^0.1.0",
8 | "react": "^16.11.0",
9 | "react-dom": "^16.11.0",
10 | "react-scripts": "^2.1.8",
11 | "styled-components": "^4.4.1",
12 | "xstate": "next"
13 | },
14 | "scripts": {
15 | "start": "react-scripts start",
16 | "build": "react-scripts build",
17 | "test": "react-scripts test",
18 | "eject": "react-scripts eject",
19 | "e2e": "jest -c jest.config.js"
20 | },
21 | "eslintConfig": {
22 | "extends": "react-app"
23 | },
24 | "browserslist": [
25 | ">0.2%",
26 | "not dead",
27 | "not ie <= 11",
28 | "not op_mini all"
29 | ],
30 | "devDependencies": {
31 | "@testing-library/react": "^9.3.1",
32 | "@xstate/test": "^0.1.0",
33 | "chai": "^4.2.0",
34 | "jest": "^24.9.0",
35 | "jest-puppeteer": "^4.3.0"
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 David Khourshid
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 |
8 | # Runtime data
9 | pids
10 | *.pid
11 | *.seed
12 | *.pid.lock
13 |
14 | # Directory for instrumented libs generated by jscoverage/JSCover
15 | lib-cov
16 |
17 | # Coverage directory used by tools like istanbul
18 | coverage
19 |
20 | # nyc test coverage
21 | .nyc_output
22 |
23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24 | .grunt
25 |
26 | # Bower dependency directory (https://bower.io/)
27 | bower_components
28 |
29 | # node-waf configuration
30 | .lock-wscript
31 |
32 | # Compiled binary addons (https://nodejs.org/api/addons.html)
33 | build/Release
34 |
35 | # Dependency directories
36 | node_modules/
37 | jspm_packages/
38 |
39 | # TypeScript v1 declaration files
40 | typings/
41 |
42 | # Optional npm cache directory
43 | .npm
44 |
45 | # Optional eslint cache
46 | .eslintcache
47 |
48 | # Optional REPL history
49 | .node_repl_history
50 |
51 | # Output of 'npm pack'
52 | *.tgz
53 |
54 | # Yarn Integrity file
55 | .yarn-integrity
56 |
57 | # dotenv environment variables file
58 | .env
59 |
60 | # next.js build output
61 | .next
62 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Model-Based Testing with `@xstate/test` and React Workshop
2 |
3 | Welcome to the workshop! To get started, follow these instructions:
4 |
5 | 1. Make sure you have Node and NPM installed.
6 | 1. Run `npm install` or `yarn install` to install all dependencies.
7 | - This is a React project bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
8 | 1. Run `npm start` to start the app.
9 |
10 | ## Goal
11 |
12 | The goal of this workshop is to demonstrate how to use `@xstate/test` with React to automate the generation of integration and end-to-end (E2E) tests of an example application.
13 |
14 | 
15 |
16 | ## Running the Tests
17 |
18 | To run the **integration tests**, run `npm test`. This will run the tests found in [`./src/App.test.js`](https://github.com/davidkpiano/xstate-test-demo/blob/master/src/App.test.js).
19 |
20 | To run the **E2E tests**, run `npm run e2e`. This will run the tests found in [`./src/App.e2e.js`](https://github.com/davidkpiano/xstate-test-demo/blob/master/src/App.test.js).
21 |
22 | ## Resources
23 |
24 | - [Github: `@xstate/test`](https://github.com/davidkpiano/xstate/tree/master/packages/xstate-test)
25 | - [Slides: Write Less Tests! From Automation to Autogeneration](https://slides.com/davidkhourshid/mbt/) (React Rally 2019)
26 | - [Article: Model-Based Testing in React with State Machines](https://css-tricks.com/?p=286484) (CSS-Tricks)
27 |
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
10 |
11 |
15 |
16 |
25 | React App
26 |
27 |
28 |
29 |
30 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | // @ts-check
2 |
3 | import React, { useReducer, useEffect } from 'react';
4 | import styled from 'styled-components';
5 |
6 | function useKeyDown(key, onKeyDown) {
7 | useEffect(() => {
8 | const handler = e => {
9 | if (e.key === key) {
10 | onKeyDown();
11 | }
12 | };
13 |
14 | window.addEventListener('keydown', handler);
15 |
16 | return () => window.removeEventListener('keydown', handler);
17 | }, [onKeyDown]);
18 | }
19 |
20 | const StyledScreen = styled.div`
21 | padding: 1rem;
22 | padding-top: 2rem;
23 | background: white;
24 | box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.1);
25 | border-radius: 0.5rem;
26 |
27 | > header {
28 | margin-bottom: 1rem;
29 | }
30 |
31 | button {
32 | background: #4088da;
33 | appearance: none;
34 | border: none;
35 | text-transform: uppercase;
36 | color: white;
37 | letter-spacing: 0.5px;
38 | font-weight: bold;
39 | padding: 0.5rem 1rem;
40 | border-radius: 20rem;
41 | align-self: flex-end;
42 | cursor: pointer;
43 | font-size: 0.75rem;
44 |
45 | + button {
46 | margin-left: 0.5rem;
47 | }
48 |
49 | &[data-variant='good'] {
50 | background-color: #7cbd67;
51 | }
52 | &[data-variant='bad'] {
53 | background-color: #ff4652;
54 | }
55 | }
56 |
57 | textarea {
58 | display: block;
59 | margin-bottom: 1rem;
60 | border: 1px solid #dedede;
61 | font-size: 1rem;
62 | }
63 |
64 | [data-testid='close-button'] {
65 | position: absolute;
66 | top: 0;
67 | right: 0;
68 | appearance: none;
69 | height: 2rem;
70 | width: 2rem;
71 | line-height: 0;
72 | border: none;
73 | background: transparent;
74 | text-align: center;
75 | display: flex;
76 | justify-content: center;
77 | align-items: center;
78 |
79 | &:before {
80 | content: '×';
81 | font-size: 1.5rem;
82 | color: rgba(0, 0, 0, 0.5);
83 | }
84 | }
85 | `;
86 |
87 | function QuestionScreen({ onClickGood, onClickBad, onClose }) {
88 | useKeyDown('Escape', onClose);
89 |
90 | return (
91 |
92 |
93 |
100 |
103 |
104 |
105 | );
106 | }
107 |
108 | function FormScreen({ onSubmit, onClose }) {
109 | useKeyDown('Escape', onClose);
110 |
111 | return (
112 | {
116 | e.preventDefault();
117 | const { response } = e.target.elements;
118 |
119 | onSubmit({
120 | value: response
121 | });
122 | }}
123 | >
124 |
125 |
143 | );
144 | }
145 |
146 | function ThanksScreen({ onClose }) {
147 | useKeyDown('Escape', onClose);
148 |
149 | return (
150 |
151 | Thanks for your feedback.
152 |
153 |
154 | );
155 | }
156 |
157 | function feedbackReducer(state, event) {
158 | // Write your reducer here
159 | }
160 |
161 | function Feedback() {
162 | const [state, dispatch] = useReducer(feedbackReducer, 'question');
163 |
164 | switch (state) {
165 | case 'question':
166 | return (
167 | dispatch({ type: 'GOOD' })}
169 | onClickBad={() => dispatch({ type: 'BAD' })}
170 | onClose={() => dispatch({ type: 'CLOSE' })}
171 | />
172 | );
173 | case 'form':
174 | return (
175 | dispatch({ type: 'SUBMIT', value })}
177 | onClose={() => dispatch({ type: 'CLOSE' })}
178 | />
179 | );
180 | case 'thanks':
181 | return dispatch({ type: 'CLOSE' })} />;
182 | case 'closed':
183 | return null;
184 | }
185 | }
186 |
187 | const StyledApp = styled.main`
188 | height: 100vh;
189 | width: 100vw;
190 | background: #f5f8f9;
191 | display: flex;
192 | justify-content: center;
193 | align-items: center;
194 |
195 | &,
196 | * {
197 | position: relative;
198 | box-sizing: border-box;
199 | }
200 | `;
201 |
202 | function App() {
203 | return (
204 |
205 |
206 |
207 | );
208 | }
209 |
210 | export default App;
211 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read http://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.1/8 is considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit http://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See http://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl)
104 | .then(response => {
105 | // Ensure service worker exists, and that we really are getting a JS file.
106 | const contentType = response.headers.get('content-type');
107 | if (
108 | response.status === 404 ||
109 | (contentType != null && contentType.indexOf('javascript') === -1)
110 | ) {
111 | // No service worker found. Probably a different app. Reload the page.
112 | navigator.serviceWorker.ready.then(registration => {
113 | registration.unregister().then(() => {
114 | window.location.reload();
115 | });
116 | });
117 | } else {
118 | // Service worker found. Proceed as normal.
119 | registerValidSW(swUrl, config);
120 | }
121 | })
122 | .catch(() => {
123 | console.log(
124 | 'No internet connection found. App is running in offline mode.'
125 | );
126 | });
127 | }
128 |
129 | export function unregister() {
130 | if ('serviceWorker' in navigator) {
131 | navigator.serviceWorker.ready.then(registration => {
132 | registration.unregister();
133 | });
134 | }
135 | }
136 |
--------------------------------------------------------------------------------