acammies
2018-04-16 90472f70666b9e69ebb9b67bb6080d0790629c96
commit | author | age
43f2f2 1 # Exercise Title
D 2
5285f8 3 > The purpose of this lab is to develop and validate a new feature using TDD; and to promote the assured feature through the pipeline.
f6d2bd 4
D 5 ---
43f2f2 6
D 7 ## Learning Outcomes
f6d2bd 8
43f2f2 9 As a learner you will be able to
f6d2bd 10
5285f8 11 * Understand the why behind TDD
D 12 * Implement a feature using TDD for frontend and backend
13 * Write end to end tests for the feature and run them in CI
43f2f2 14
D 15 ## Tools and Frameworks
f6d2bd 16
43f2f2 17 > Name of tool - short description and link to docs or website
D 18
5285f8 19 1.  [Jest](https://facebook.github.io/jest/) - Zero configuration testing platform
D 20 Jest is used by Facebook to test all JavaScript code including React applications. One of Jest's philosophies is to provide an integrated "zero-configuration" experience. We observed that when engineers are provided with ready-to-use tools, they end up writing more tests, which in turn results in more stable and healthy code bases.
21 1.  [Vue Test Utils](https://vue-test-utils.vuejs.org/en/) - Vue Test Utils is the official unit testing utility library for Vue.js.
22 1.  [Nightwatch.js](http://nightwatchjs.org/) - Nightwatch.js is an easy to use Node.js based End-to-End (E2E) testing solution for browser based apps and websites. It uses the powerful W3C WebDriver API to perform commands and assertions on DOM elements.
23 1.  [Mocha](https://mochajs.org/) - Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases. Hosted on GitHub.
24 1.  [Sinon](http://sinonjs.org/) - Standalone test spies, stubs and mocks for JavaScript. 
25 Works with any unit testing framework.
43f2f2 26
D 27 ## Big Picture
f6d2bd 28
43f2f2 29 This exercise begins cluster containing blah blah
D 30
f6d2bd 31 ---
43f2f2 32
D 33 ## 10,000 Ft View
f6d2bd 34
5285f8 35 > The goal of this exercise is to add a new component to the application using TDD to create and validate it's behaviour. The User story we have been given is as follows:
43f2f2 36
5285f8 37 *As a doer I want to mark todos as important so that I can keep track of and complete high prirority todos first*
f6d2bd 38
5285f8 39 _Acceptance Criteria_
D 40 - [ ] should be doable with a single click
41 - [ ] should add a red flag against the todo when marked important
42 - [ ] should remove the red colour flag on the flag when important removed
43 - [ ] should not affect existing todos
44
45 _On page load:_
46 - [ ] should display existing todos that are not marked important
47 - [ ] should display existing todos that are marked important with an red flag
43f2f2 48
D 49 ## Step by Step Instructions
f6d2bd 50
5285f8 51 > This is a fairly structured guide with references to exact filenames and sections of text to be added.
43f2f2 52
f6d2bd 53 ### Part 1 - Tests in our Pipeline
D 54
bc2216 55 > _In this exercise we will improve the pipeline created already by adding some unit tests for the frontend & backend along with some end to end tests (e2e) to validate the full solution_
43f2f2 56
bc2216 57 #### Part 1a - Unit tests
D 58
f6d2bd 59 2.  TODO - show tests running locally etc (fe and api)
bc2216 60
f6d2bd 61 3.  TODO - add tests to jenkins with screenshots etc.
bc2216 62
D 63 #### Part 1b - End to End tests (e2e)
64
f6d2bd 65 2.  Add new part to the dev pipeline (`dev-todolist-fe-e2e`)
bc2216 66
f6d2bd 67 3.  Add tests and reports to Jenkins
bc2216 68
5285f8 69 ### Part 2 - TodoList new feature
f6d2bd 70
bc2216 71 > _In this exercise we will introduce a new feature to create an important flag on the todos. In order to be able to build and test our feature we will use TDD_
D 72
5285f8 73 *As a doer I want to mark todos as important so that I can keep track of and complete high prirority todos first*
D 74
75 _Acceptance Criteria_
76 - [ ] should be doable with a single click
77 - [ ] should add a red flag against the todo when marked important
78 - [ ] should remove the red colour flag on the flag when important removed
79 - [ ] should not affect existing todos
80
81 _On page load:_
82 - [ ] should display existing todos that are not marked important
83 - [ ] should display existing todos that are marked important with an red flag
bc2216 84
f6d2bd 85 #### Part 1a - Create todolist-api tests
bc2216 86
5285f8 87 > Using [Mocha](https://mochajs.org/) as our test runner; we will now write some tests for backend functionality to persist our important-flag. The changes required to the backend are minimal but we will use TDD to create our test first, then implement the functionality.
f6d2bd 88
D 89 3.  Create a new branch in your `todolist-api` app for our feature and push it to the remote
bc2216 90 ```bash
D 91 $ git checkout -b feature/important-flag
92 $ git push -u origin feature/important-flag
43f2f2 93 ```
D 94
f6d2bd 95 3.  Navigate to the `server/api/todo/todo.spec.js` file. This contains all of the existing todo list api tests. These are broken down into simple `describe("api definition", function(){})` blocks which is BDD speak for how the component being tested should behave. Inside of each `it("should do something ", function(){})` statements we use some snappy language to illustrate the expected behaviour of the test. For example a `GET` request of the api is described and tested for the return to be of type Array as follows.
D 96 ```javascript
97 describe("GET /api/todos", function() {
98     it("should respond with JSON array", function(done) {
99         request(app)
100         .get("/api/todos")
101         .expect(200)
102         .expect("Content-Type", /json/)
103         .end(function(err, res) {
104             if (err) return done(err);
105             // Test goes here
106             res.body.should.be.instanceof(Array);
107             done();
108         });
5285f8 109       });
f6d2bd 110 });
D 111 ```
112 where:
5285f8 113 _ `describe` is used to group tests together into a collection asserting some feature; for example the get all todos api.
D 114 _ `it` is an individual test statement and should contain an `expect` or a `should` statement asserting behaviour of the API under test.
115 _ `request` is a library for making http calls to the api.
116 _ `.expect(200)` asserts the HTTP Return Code
117 _ `res.body.should.be.instanceof(Array);` is the actual test call
118 _ `done();` tells the test runner that `mocha` has finished execution. This is needed as the http calls are asynchronous.
43f2f2 119
5285f8 120 3.  With this knowledge; let's implement our test for the `important` flag. We expect the fronted to introduce a new property on each `todo` that gets passed to the backend called `important`. The API will need to handle this new property and pass it into the mongodb. Let's begin implementing this functionality by writing our test case. Navigate to the `PUT /api/todos` section of the test which should be at the bottom ![todo-api-tests](../images/exercise3/todo-api-tests.png).
f6d2bd 121
5285f8 122 3.  Before writing our test; let's first make sure all the existing tests are passing.
D 123 ```bash
f6d2bd 124 $ npm run test
D 125 ```
126
5285f8 127 3.  With all the tests passing; let's add our new one. For ease of completing this exercise a template of a new test has been written at the very end of the file. A PUT request responds in our API with the data that it just updated, so provided that MongoDB accepted the change, it will respond with an object that has the `important` property on it. To write our test; edit the `it("should ....", function(done) {` by completing the following:
f6d2bd 128     * Edit the `it("should ...")` to describe the imporant flag we're testing
D 129     * Edit the `.send()` to include `important: true` property
130     * Add a new test assertion to check that `res.body.important` is `true` below the `// YOUR TEST GO HERE` line.
131 ```javascript
5285f8 132 it("should mark todo as important and persist it", function(done) {
f6d2bd 133     request(app)
D 134       .put("/api/todos/" + todoId)
5285f8 135       .send({
D 136         title: "LOVE endpoint/server side testing!",
137         completed: true,
138         important: true
139       })
f6d2bd 140       .expect(200)
D 141       .expect("Content-Type", /json/)
142       .end(function(err, res) {
5285f8 143           if (err) return done(err);
D 144           res.body.should.have.property("_id");
145           res.body.title.should.equal("LOVE endpoint/server side testing!");
146           // YOUR TEST GO HERE
147           res.body.important.should.equal(true);
148           done();
f6d2bd 149       });
5285f8 150 });
f6d2bd 151 ```
D 152
5285f8 153 3.  Run your test. It should fail.
D 154 ```bash
f6d2bd 155 $ npm run test
D 156 ```
157 ![fail-mocha](../images/exercise3/fail-mocha.png)
158
5285f8 159 3.  With our test now failing; let's implement the feature. This is quite a simple change; all we need to do it update the `server/api/todo/todo.model.js` to allow an additional property on the schema called `important` of type Boolean.
f6d2bd 160 ```javascript
D 161 const TodoSchema = new Schema({
5285f8 162   title: String,
D 163   completed: Boolean,
164   important: Boolean
f6d2bd 165 });
D 166 ```
167
5285f8 168 3.  With your changes to the Database schema updated; re-run your tests.
D 169 ```bash
f6d2bd 170 $ npm run test
D 171 ```
172
5285f8 173 3.  Commit your code to the `feature/important-flag` branch and then merge onto the `develop` branch as follows
f6d2bd 174 <p class="tip">
D 175 NOTE - At this point in a residency we would peer review the code before pushing it to develop or master branch!
176 </p>
5285f8 177 ```bash
f6d2bd 178 $ git add .
D 179 $ git commit -m "ADD backend schema updates"
180 $ git checkout develop
181 $ git merge feature/important-flag
182 $ git push --all
183 ```
184
185 #### Part 1b - Create todolist-fe tests
5285f8 186 > Using [Jest](https://facebook.github.io/jest/) as our test runner and the `vue-test-utils` library for managing our vue components; we will now write some tests for fronted functionality to persist our important-flag. The changes required to the front end are quite large but we will use TDD to create our test first, then implement the functionality. 
f6d2bd 187
5285f8 188 Our TodoList App uses `vuex` to manage the state of the apps' todos and `axios` HTTP library to connect to the backend. `Vuex` is an opinionated framework for managing application state and has some key design features you will need to know to continue with the exercise. 
f6d2bd 189
5285f8 190 In `vuex` the application state is managed by a `store`. The `store` houses all the todos we have retrieved from the backend as well as the `getter` methods for our array of `todos`. In order to make changes to the store, we could call the store directly and update each todo item but as earlier said; vuex is an opinionated module with it's own way of updating the store. It is bad practice to call the store directly. 
D 191
192 There are two parts of the lifecycle to updating the store, the `actions` & `mutations`. When the user clicks a todo to mark it as complete; the `actions` are called. An action could involve a call to the backend or some pre-processing of the data. Once this is done, the change is committed to the store by calling the `mutation` function. A store should only ever be manipulated through a mutation function. Calling the mutation will then update the todo object in the apps local store for rendering in the view.
193
194 For example; when marking a todo as done in the UI, the following flow occurs
195     * The `TodoItem.vue` calls the `markTodoDone()` function which dispatches an event to the store.
196     * This calls the `updateTodo()` function in the `actions.js` file
197     * The action will update the backend db (calling our `todolist-api`) with our updated todo object.
198     * The action will commit the change to the store by calling the mutation method `MARK_TODO_COMPLETED`
199     * The `MARK_TODO_COMPLETED` will directly access the store object and update it with the new state value
200     * The `ListOfTodos.vue` component is watching the store for changes and when something gets updated it re-renders the `TodoItem.vue`.
201
202 3. Let's implement our feature by first creating a branch. Our new feature, important flag will behave in the same way as the `MARK_TODO_COMPLETED`. Create a new branch in your `todolist-fe` app for our feature and push it to the remote
f6d2bd 203 ```bash
D 204 $ git checkout -b feature/important-flag
205 $ git push -u origin feature/important-flag
206 ```
bc2216 207
5285f8 208 3. Let's get our tests running by executing a `--watch` on our tests. This will keep re-running our tests everytime there is a file change. All the tests should be passing when we begin
D 209 ```bash
210 $ npm run test -- --watch
211 ```
212
bc581a 213 3. There are three places we will add new tests to validate our function behaves as expected against the acceptance criteria from Feature Story supplied to us. We will need to write tests for our `TodoItem.vue` to handle having a red flag and that it is clickable. Our app is going to need to persist the changes in the backend so we'll want to make changes to our `actions.js` and `mutations.js` to keep the api and local copy of the store in sync. Let's start with our `TodoItem.vue` component. Open the `tests/unit/vue-components/TodoItem.spec.js` file. This has been templated with some example test to correspond with our A/Cs for speed of doing the lab. Find the describe block for our important flag tests. It is setup already with a `beforeEach()` hook for test setup.
5285f8 214 ![important-flag-before](../images/exercise3/important-flag-before.png)
D 215
216 3. Each of our test cases has it's skeleton in place already for example the `TodoItem.vue` component takes a property of `todos` when rendering. This setup is already done for each of our tests so all we have to do is fill in our assertions.
217 ![todoitem-skeleton-tests](../images/exercise3/todoitem-skeleton-tests.png)
218
219 3. Let's implement the first test `it("should render a button with important flag"`. This test will assert if the button is present on the page and it contains the `.important-flag` CSS class. To implement this; add the expect statement as follows.  
220 ```javascript
221   it("should render a button with important flag", () => {
222     const wrapper = mount(TodoItem, {
223       propsData: { todoItem: importantTodo }
224     });
225     // TODO - test goes here!
226     expect(wrapper.find(".important-flag").exists()).toBe(true);
227   });
228 ```
229
230 3. Save the file and we should see in our test watch the test case has started failing because we have not yet implemented the feature!
231 ![todoitem-fail-test](../images/exercise3/todoitem-fail-test.png)
232
233 3. With a basic assertion in place, let's continue on to the next few tests. We want the important flag to be red when an item in the todolist is marked accordingly. Conversely we want it to be not red when false. Let's create a check for `.red-flag` CSS property to be present when imporant is true and not when false.
234 ```javascript
235   it("should set the colour to red when true", () => {
236     const wrapper = mount(TodoItem, {
237       propsData: { todoItem: importantTodo }
238     });
239     // TODO - test goes here!
240     expect(wrapper.find(".red-flag").exists()).toBe(true);
241   });
242   it("should set the colour to not red when false", () => {
243     importantTodo.important = false;
244     const wrapper = mount(TodoItem, {
245       propsData: { todoItem: importantTodo }
246     });
247     // TODO - test goes here!
248     expect(wrapper.find(".red-flag").exists()).toBe(false);
249   });
250 ```
251
bc581a 252 3. Finally, we want to make the flag clickable and for it to call a function to update the state. The final test in the `TodoItem.spec.js` we want to create should simulate this behaviour. Implement the `it("call makImportant when clicked", () ` test by first simulating the click of our important-flag and asserting the function `markImportant()` to write is executed.
5285f8 253 ```javascript
D 254   it("call makImportant when clicked", () => {
255     const wrapper = mount(TodoItem, {
256       methods,
257       propsData: { todoItem: importantTodo }
258     });
259     // TODO - test goes here!
260     const input = wrapper.find(".important-flag");
261     input.trigger("click");
262     expect(methods.markImportant).toHaveBeenCalled();
263   });
264 ```
265
266 3. With our tests written for the feature's UI component, let's implement our code to pass the tests. Open up the `src/components/TodoItem.vue`. Each vue file is broken down into 3 sections
267     * The `<template></template>` contains the HTML of our component. This could include references to other Components also
268     * The `<script></script>` contains the JavaScript of our component and is essentially the logic for our component. It defines things like `properties`, `methods` and other `components`
269     * The `<style></style>` contains the encapsulated CSS of our component
270 Underneath the `</md-list-item>` tag, let's add a new md-button. Add a `.important-flag` class on the `md-button` and put the svg of the flag provided inside it.
271 ```html
272     </md-list-item>
273     <!-- TODO - SVG for use in Lab3 -->
274     <md-button class="important-flag">
275         <svg height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" ><path d="M0 0h24v24H0z" fill="none"/><path d="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z"/></svg>
276     </md-button>
277 ```
278
279 3. We should now see the first of our failing tests has started to pass. Running the app locally (using `npm run serve`) should show the flag appear in the UI. It is clickable but won't fire any events and the colour is not red as per our requirement. Let's continue to implement the colour change for the flag. On our `<svg/>` tag, add some logic to bind the css to the property of a `todo.important` by adding ` :class="{'red-flag': todoItem.important}"  `. This logic will apply the CSS class when `todo.important`  is true.
280 ```html
281 <md-button class="important-flag">
282     <svg :class="{'red-flag': todoItem.important}"  height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" ><path d="M0 0h24v24H0z" fill="none"/><path d="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z"/></svg>
283 </md-button>
284 ```
285
286 3. More tests should now be passing. Let's wire the click of the flag to an event in Javascript. In the methods section of the `<script></script>` tags in the Vue file, implement the `markImportant()`. We want to wire this to the action to updateTodo, just like we have in the `markCompleted()` call above it. We also need to pass and additional property to this method call `imporant`
287 ```javascript
288     markImportant() {
289       // TODO - FILL THIS OUT IN THE LAB EXERCISE
290       this.$store.dispatch("updateTodo", {id: this.todoItem._id, important: true});
291       console.info("INFO - Mark todo as important ", this.todoItem.important);
292     },
293 ```
294
295 3. Finally - let's connect the click button in the DOM to the Javascript function we've just created. In the template, add a click handler to the md-button to call the function `markImportant()` by adding ` @click="markImportant()"` to the `<md-button> tag 
296 ```html
297     <!-- TODO - SVG for use in Lab3 -->
298     <md-button class="important-flag" @click="markImportant()">
299         <svg :class="{'red-flag': todoItem.important}"  height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" ><path d="M0 0h24v24H0z" fill="none"/><path d="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z"/></svg>
300     </md-button>
301 ```
302
303 3. The previously failing tests should have started to pass now. With this work done, let's commit our code. On the terminal, run 
304 ```bash
305 $ git add .
306 $ git commit -m "Implementing the todoitem flag"
307 $ git push
308 ```
309
bc581a 310 3. If we try to use our important flag, we should see it's still not behaving as expected; this is because we're not updating the state of the app in response to the click event. We need to implement the `actions` and `mutations` for our feature. Let's start with the tests. Open the `tests/unit/javascript/actions.spec.js` and navigate to the bottom of the file. Our action should should commit the `MARK_TODO_IMPORTANT` to the mutations. Scroll to the end of the test file and implement the skeleton test by adding `expect(commit.firstCall.args[0]).toBe("MARK_TODO_IMPORTANT");` as the assertion.
5285f8 311 ```javascript
D 312   it("should call MARK_TODO_IMPORTANT", done => {
313     const commit = sinon.spy();
314     state.todos = todos;
315     actions.updateTodo({ commit, state }, { id: 1, important: true }).then(() => {
316         // TODO - test goes here!
317         expect(commit.firstCall.args[0]).toBe("MARK_TODO_IMPORTANT");
318         done();
319     });
320   });
321 ```
322
bc581a 323 3. We should now have more failing tests, let's fix this by adding the call from our action to the mutation method. Open the `src/store/actions.js` file and scroll to the bottom to the `updateTodo()` method. Complete the if block by adding `commit("MARK_TODO_IMPORTANT", i);` as shown below.
5285f8 324 ```javascript
D 325 updateTodo({ commit, state }, { id, important }) {
326     let i = state.todos.findIndex(todo => todo._id === id);
327     if (important) {
328         // TODO - add commit imporant here!
329         commit("MARK_TODO_IMPORTANT", i);
330     } else {
331         commit("MARK_TODO_COMPLETED", i);
332     }
333 ```
334
335 3. Finally, let's implement the `mutation` for our feature. Again, starting with the tests..... Open the `tests/unit/javascript/mutations.spec.js`. Our mutation method is responsible to toggling the todo's `important` property between true and 
336 false. Let's implement the tests for this functionality by setting imporant to be true and calling the method expecting the inverse and setting it to false and calling the method expecting the inverse. 
337 ```javascript
338   it("it should MARK_TODO_IMPORTANT as false", () => {
339     state.todos = importantTodos;
340     // TODO - test goes here!
341     mutations.MARK_TODO_IMPORTANT(state, 0);
342     expect(state.todos[0].important).toBe(false);
343   });
344
345   it("it should MARK_TODO_IMPORTANT as true", () => {
346     state.todos = importantTodos;
347     // TODO - test goes here!
348     state.todos[0].important = false;
349     mutations.MARK_TODO_IMPORTANT(state, 0);
350     expect(state.todos[0].important).toBe(true);
351   });
352 ```
353
354 3. With our tests running and failing, let's implement the feature to their spec. Open the `src/store/mutations.js` and add another function called `MARK_TODO_IMPORTANT` below the `MARK_TODO_COMPLETED` to toggle `todo.important` between true and false.
355 ```javascript
356   MARK_TODO_IMPORTANT(state, index) {
357     console.log("INFO - MARK_TODO_IMPORTANT");
358     state.todos[index].important = !state.todos[index].important;
359   }
360 ```
361
362 3. All our tests should now be passing. On the watch tab where they are running, hit `u` to re-run all tests and update any snapshots.
363
364 3. With all our tests now passing, let's commit our code. On the terminal, run
365 ```bash
366 $ git add .
367 $ git commit -m "Implementing the store and actions"
368 $ git push
369 ```
370
371 3. Before running a build in Jenkins, let's add our tests and code to the develop branch
372 <p class="tip">
373 NOTE - At this point in a residency we would peer review the code before pushing it to develop or master branch!
374 </p>
375 ```bash
376 $ git checkout develop
377 $ git merge feature/important-flag
378 $ git push --all
379 ```
380
381 3. Run a build in Jenkins. We should see the test trend increase as we've added more tests. Validate the flag is working as expected.
382
bc2216 383 #### Part 1c - Create todolist e2e tests
D 384
5285f8 385 3.  TODO !!
43f2f2 386
f6d2bd 387 ---
43f2f2 388
D 389 ## Extension Tasks
f6d2bd 390
43f2f2 391 > _Ideas for go-getters. Advanced topic for doers to get on with if they finish early. These will usually not have a solution and are provided for additional scope._
D 392
f6d2bd 393 * Add Auth to your application
D 394 * Do some other stuff
43f2f2 395
D 396 ## Additional Reading
f6d2bd 397
43f2f2 398 > List of links or other reading that might be of use / reference for the exercise
D 399
400 ## Slide links
f6d2bd 401
D 402 > link back to the deck for the supporting material