You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Day 5 notes - GitHub stargazing with spies and stubs
2
+
3
+
## What you'll do
4
+
5
+
Today you're going to look at calling the GitHub API using a HTTP request
6
+
7
+
## Install request-promise
8
+
9
+
You're going to make a HTTP request to the GitHub API using `request-promise`. This is a simple HTTP request client with Promise support. Install `request-promise` (and also `request` as it is a peer dependency) using `npm`:
10
+
11
+
```shell
12
+
npm install --save request request-promise
13
+
```
14
+
15
+
## Spies vs Stubs
16
+
17
+
Spies and stubs are sometimes confused but they serve two different purposes. **Spies** live up to their name and the spy on functions but don't alter the function's behaviour at all. We can use them to tell us that something has been called and how. **Stubs** are similar to spies, and they support the sinon spy API, but they also alter the behaviour of the function. This means you can define how the function will respond. This allows you to better test the happy and unhappy paths in your code.
18
+
19
+
### Create the code
20
+
21
+
Create a new module in the `src` directory called `day5.js` and corresponding test file in the `test` directory called `day5.test.js`:
22
+
23
+
```javascript
24
+
importrequestPromisefrom'request-promise';
25
+
26
+
functionday5(owner, repository) {
27
+
});
28
+
29
+
exportdefaultday5;
30
+
```
31
+
32
+
```javascript
33
+
import {expect} from'chai';
34
+
importsinonfrom'sinon';
35
+
importrequestPromisefrom'request-promise';
36
+
importday5from'../src/day5';
37
+
38
+
describe('day5 tests', () => {
39
+
});
40
+
```
41
+
42
+
### Spy on the GitHub API
43
+
44
+
Let's spy on the GitHub API request and confirm that it's called once. Set up the spy to inspect `requestPromise.get` for the GET request we'll make to the API. You can then write a test that confirms that the spy was called only once.
45
+
46
+
```javascript
47
+
let spyRequestGet;
48
+
49
+
beforeEach(() => {
50
+
spyRequestGet =sinon.spy(requestPromise, 'get');
51
+
});
52
+
53
+
afterEach(() => {
54
+
spyRequestGet.restore();
55
+
});
56
+
57
+
it('should call the expected endpoint once', () => {
0 commit comments