Dia 65/2019 - Karma, Chai e Sinon

Desafio #92daysofcode que fiz no final de 2019. Nesse artigo temos o dia 65, mostrando o uso do Karma, Chai e Sinon.

Código

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const process = require('process');
process.env.CHROME_BIN = require('puppeteer').executablePath();

module.exports = config => {
config.set({
frameworks: ['mocha', 'chai', 'sinon'],
files: [
'cart.js',
'day.js'
],
preprocessors: {
'cart.js': ['webpack', 'coverage'],
'day.js': ['webpack']
},
webpack: {
mode: 'development',
module: {
rules: [
{
test: /\.(cart.js|day.js)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
["@babel/preset-env", {
"targets": { "browsers": ["last 2 chrome versions"] }
}]
]
}
}
}
]
},
watch: true
},
reporters: ['progress', 'coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromeHeadless'],
singleRun: false,
coverageReporter: {
type: 'html',
dir: 'coverage/'
}
});
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Cart {
constructor(price, promoCode) {
this.hardCodedPromoCode = 'Hello';
this.price = price;
this.totalPrice = price;
this.promoCode = promoCode;

this.checkout();
}

applyPromoValue(promoValue) {
this.totalPrice = this.price - promoValue;
this.render();
}

getPromoValue() {
const url = 'http://www.mocky.io/v2/5de8a8523100005d006b12db';

return fetch(url)
.then(response => response.json())
.then(json => json.value)
.catch(() => 0);
}

validatePromoCode() {
let promoValue = 0;
const promoCode = this.promoCode;

if (promoCode === this.hardCodedPromoCode) {
promoValue = this.getPromoValue(2);
this.applyPromoValue(promoValue);
} else {
this.applyPromoValue(promoValue);
}
}

checkout() {
this.validatePromoCode();
}

render() {
const $view = document.querySelector('[data-js="total"]');
$view.innerHTML = this.totalPrice.toFixed(2);
}
}

export default Cart;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Karma - Spectacular Test Runner for Javascript
// https://karma-runner.github.io/latest/index.html

// Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.
// https://www.chaijs.com/

// Standalone test spies, stubs and mocks for JavaScript. Works with any unit testing framework.
// https://sinonjs.org/

import Cart from './cart';

const jsonOk = body => {
const mockResponse = new window.Response(JSON.stringify(body), {
status: 200,
headers: {
'Content-type': 'application/json'
}
});

return Promise.resolve(mockResponse);
}

describe('Cart', () => {
let sandbox;

before(() => {
const fixture = `
<form>
<input type="text" name="promoCode" data-js="promoCode">
<input type="hidden" name="price" data-js="price" value="10.00">
<button type="submit">Ok</button>
</form>
<p>Price: <strong>10.00</strong></p>
<p>Total: <strong>$<span data-js="total">10.00</span></strong></p>
`;

document.body.insertAdjacentHTML(
'afterbegin',
fixture
);
});

beforeEach(() => {
sandbox = sinon.createSandbox();
});

afterEach(() => {
sandbox.restore();
});

describe('Checkout', () => {
let cart;

context('when promo code applicable', () => {
beforeEach(() => {
const price = 30.00;
const promoCode = 'Hello';

cart = new Cart(price, promoCode);

sandbox.stub(cart, 'checkout');
sandbox.stub(window, 'fetch');

window.fetch.returns(jsonOk({
value: 30
}));
});

afterEach(() => {
window.fetch.restore();
});

it('price exists', () => {
expect(cart.price).to.be.equal(30);
});

it('promo code exists', () => {
expect(cart.promoCode).to.be.equal('Hello');
});

it('get promo code value', async () => {
await cart.getPromoValue()
.then(value => expect(value).to.be.equal(30));
});

it('validate promo code', () => {
const applyPromoValueStub = sandbox.stub(cart, 'applyPromoValue');

cart.validatePromoCode();

expect(applyPromoValueStub.called).to.be.ok;
});

it('Apply promo code to price', () => {
sandbox.stub(cart, 'render');

const applyPromoValueSpy = sandbox.spy(cart, 'applyPromoValue');
const promoValue = 20;

cart.applyPromoValue(promoValue);

expect(applyPromoValueSpy.calledWith(20)).to.be.ok;
expect(cart.totalPrice).to.be.equal(10);
});

it('render formatted price in the view', () => {
const promoValue = 20;
cart.applyPromoValue(promoValue);
const elTextContent = document.querySelector('[data-js="total"]').textContent;

expect(elTextContent).to.be.equal('10.00');
});
});
});
});

Conclusão

A postagem original pode ser vista no meu Instagram e o código está acessível no meu Github.

Relacionados

Ao fechar este aviso ou continuar navegando no site Nerd Calistênico, você aceita o uso de cookies.

Este site usa cookies para assegurar a melhor experiência para os nossos usuários. Consulte nossa política de privacidade.

Uma nova versão está disponível. Clique aqui para atualizar.