Skip to content

Instantly share code, notes, and snippets.

@mauricioklein
Created September 28, 2017 13:24
Show Gist options
  • Save mauricioklein/b0dd5768bce0075232729596dc71a83f to your computer and use it in GitHub Desktop.
Save mauricioklein/b0dd5768bce0075232729596dc71a83f to your computer and use it in GitHub Desktop.
import request from 'superagent';
export const getWeatherForCity = (city, country) => {
return new Promise((resolve, reject) => {
request
.get('http://api.openweathermap.org/data/2.5/weather')
.query({
q: `${city},${country}`,
units: 'metric',
APPID: 'ABC123'
})
.end((err, res) => {
if (err) { reject (err) }
else { resolve(res.body) }
})
})
}
// ./superagent-mock-config.js file
const cityResponse = {
"coord": {
"lon": 13.41,
"lat": 52.52
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 17,
"pressure": 1026,
"humidity": 67,
"temp_min": 17,
"temp_max": 17
},
"visibility": 10000,
"wind": {
"speed": 4.1,
"deg": 100
},
"clouds": {
"all": 0
},
"dt": 1506594000,
"sys": {
"type": 1,
"id": 4892,
"message": 0.0021,
"country": "DE",
"sunrise": 1506574995,
"sunset": 1506617363
},
"id": 2950159,
"name": "Berlin",
"cod": 200
}
const rules = [
{
pattern: 'http://api.openweathermap.org/data/2.5/weather(.*)',
fixtures: function (match, params, headers, context) {
// City search: success
if (match[1] === '?q=Berlin%2CDE&units=metric&APPID=ABC123') {
return cityResponse
}
// City search: failure
if (match[1] === '?q=Foo%2CBar&units=metric&APPID=ABC123') {
throw new Error(500);
}
},
get: function (match, data) {
return {
body: data
};
}
}
];
module.exports = {
cityResponse: cityResponse,
rules: rules
}
import { getWeatherForGeoloc, getWeatherForCity } from 'api'
import request from 'superagent';
import * as apiMocks from 'mocks'
describe('API', () => {
var mock = null
beforeEach(() => mock = require('superagent-mock')(request, apiMocks.rules))
afterEach(() => mock.unset())
describe('#getWeatherForCity', () => {
it('should process success result', () => {
getWeatherForCity('Berlin', 'DE').then(body => {
expect(body).toEqual(apiMocks.cityResponse)
})
})
it('should process failure result', () => {
getWeatherForCity('Foo', 'Bar').then(() => {},
err => expect(err).toEqual(Error(500))
)
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment