SlideShare a Scribd company logo
Unit Tests
In
Tappero Gregory
2016 - WyzAnt.
Tooling.
{
"karma-mocha": "^0.2.1",
"karma-chai": "^0.1.0",
"karma-chai-as-promised": "^0.1.2",
"karma-sinon": "^1.0.4",
"karma-sinon-chai": "^1.2.0",
"karma-sinon-stub-promise": "^1.0.0",
"whatwg-fetch": "^0.11.0"
"fetch-mock": "^4.1.0",
}
Testing a filter.
import { prettybytes } from 'src/filters';
describe('Filter "prettybytes".', () => {
it('Prettybytes shows the right KB, MB, GB, TB unit.', () => {
expect(prettybytes(1024)).to.equal('1 KB');
expect(prettybytes(1048576)).to.equal('1 MB');
expect(prettybytes(1048576*1024)).to.equal('1 GB');
expect(prettybytes(1048576*1048576)).to.equal('1 TB');
expect(prettybytes(230)).to.equal('230 Bytes');
});
});
Testing an API call, mocking fetch.
import { authentify } from 'src/store/actions/auth';
import fetchMock from 'fetch-mock';
import { fetchUserToken } from 'src/api/web';
describe('Authentify action', () => {
let sandbox;
beforeEach(() => {
sandbox = sinon.sandbox.create();
});
afterEach(() => {
sandbox.restore();
fetchMock.restore();
});
it('FetchUserToken should eventually resolve with a token.', () => {
fetchMock.mock('/login/getaccesstoken/', { Model: ' ' });
return fetchUserToken().should.eventually.equal(' ');
});
});
Testing a component (1/2).
import Vue from 'vue';
import FinalCountdown from 'src/components/workflow/FinalCountdown';
describe('workflow/FinalCountDown component.', () => {
const getComponent = (date) => {
let vm = new Vue({
template: '<div><final-countdown v-ref:component :date="date"></final-countdown></div>',
components: {
FinalCountdown
},
data: {
date
}
});
return vm;
};
...
Testing a component (2/2).
it('Should render correctly with a date in the future.', () => {
const tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
const vm = getComponent(tomorrow).$mount();
expect(vm.$el).to.be.ok;
// Counter should show 23:59:59
// timeUntilExpiration is a component method.
expect(vm.$refs.component.timeUntilExpiration()).to.equal('23:59:59');
// Priority should be normal.
expect(vm.$refs.component.priorityLevel()).to.equal('normal');
});
Testing a component property change.
it('Should be valid only when a radio option is selected.', () => {
const vm = getComponent('Bob').$mount();
const component = vm.$refs.component;
expect(component.isFormValid).to.be.false;
component.picked = 3;
component.$nextTick(() => {
expect(component.isFormValid).to.be.true;
});
});
Testing a component event.
it('Send should dispatch "declinedWorkflowTask" with the choice payload.', () => {
const vm = getComponent('Bob').$mount();
const component = vm.$refs.component;
let spy = sinon.spy();
vm.$on('declinedWorkflowTask', spy);
component.sendReply();
expect(spy).to.have.been.calledWith({
choice: null,
text: ''
});
});
Testing a component ready() hook.
it('Should focus on textarea when ready.', (done) => {
const vm = getComponent();
const component = vm.$refs.component;
// Action triggered by Message Template child component.
fetchMock.mock('/tutor/templates', [{ title: 'template A', body: 'AAA' },
{ title: 'template B', body: 'BBB' }]);
// Triggers ready() on our component.
vm.$appendTo(document.body);
component.$nextTick(() => {
expect(document.activeElement).to.equal(component.$els.textarea);
done();
})
});
Testing with a Vuex store.
import store from 'src/store';
describe('workflow/WorkflowAccept component.', () => {
// Update store states here or import from fixtures.
store.state.availability = { … };
const getComponent = () => {
let vm = new Vue({
template: '<div><workflow-accept v-ref:component></workflow-accept></div>',
components: {
WorkflowAccept
},
// Inject store here.
store: store
});
return vm.$mount();
};
Testing a Vuex action (1/2).
import { sendInitialDirectContactResponse } from 'src/store/actions/workflow';
import store from 'src/store';
const state = store.state;
import { testAction } from './helper';
describe('sendInitialDirectContactResponse action.', () => {
beforeEach(() => {
state.workflow.workflowTask = {
id: 1,
conversationThread: {
id: 2,
},
initialDirectContact: {
id: 3,
},
};
...
});
Testing a Vuex action (2/2).
it('Should dispatch the right mutations.', (done) => {
testAction(sendInitialDirectContactResponse, [1, 1, 'test'], state, [
{ name: 'DELETE_WORKFLOW_TASK', payload: [1] },
{ name: 'ADD_CONVERSATION_THREAD_TO_TOP' },
{ name: 'UPDATE_CONVERSATION_THREAD' },
], done);
});
it('Should not dispatch ADD_CONVERSATION_THREAD_TO_TOP if ...', (done) => {
state.app.menuSelection = 'archived';
testAction(sendInitialDirectContactResponse, [1, 1, 'test'], state, [
{ name: 'DELETE_WORKFLOW_TASK', payload: [1] },
], done);
});
Testing a Vuex action - testaction.js (1/2).
// Helper for testing action with expected mutations.
export function testAction(action, args, state, expectedMutations, done) {
let count = 0;
// mock dispatch
const dispatch = (name, ...payload) => {
const mutation = expectedMutations[count];
expect(mutation.name).to.equal(name);
// if our mutation has a payload and our expected mutation
// wants us to assert this payload.
if (payload && mutation.payload) {
expect(mutation.payload).to.deep.equal(payload);
}
count++;
if (count === expectedMutations.length) {
done();
}
Testing a Vuex action - testaction.js (2/2)
// ...
if (count > expectedMutations.length) {
// Missing non expected mutations.
// List all expected mutations!
expect(count).to.equal(expectedMutations.length);
}
}
// call the action with mocked store and arguments
action({ dispatch, state }, ...args);
// check if no mutations should have been dispatched
if (count === 0) {
expect(expectedMutations.length).to.equal(0);
done();
}
};

More Related Content

PPTX
Testing frontends with nightwatch & saucelabs
Tudor Barbu
 
PDF
20160905 - BrisJS - nightwatch testing
Vladimir Roudakov
 
PDF
Introduction to Protractor
Jie-Wei Wu
 
PDF
Keeping the frontend under control with Symfony and Webpack
Ignacio Martín
 
PDF
Building and deploying React applications
Astrails
 
PDF
Better Testing With PHP Unit
sitecrafting
 
PDF
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Ryan Weaver
 
KEY
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
Testing frontends with nightwatch & saucelabs
Tudor Barbu
 
20160905 - BrisJS - nightwatch testing
Vladimir Roudakov
 
Introduction to Protractor
Jie-Wei Wu
 
Keeping the frontend under control with Symfony and Webpack
Ignacio Martín
 
Building and deploying React applications
Astrails
 
Better Testing With PHP Unit
sitecrafting
 
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Ryan Weaver
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 

What's hot (20)

PDF
Workshop 14: AngularJS Parte III
Visual Engineering
 
PDF
Unit Testing Express and Koa Middleware in ES2015
Morris Singer
 
PDF
The JavaFX Ecosystem
Andres Almiray
 
PDF
Intro to testing Javascript with jasmine
Timothy Oxley
 
PDF
Workshop 12: AngularJS Parte I
Visual Engineering
 
PPTX
Rapid prototyping and easy testing with ember cli mirage
Krzysztof Bialek
 
PPTX
Building Progressive Web Apps for Windows devices
Windows Developer
 
PDF
Containers & Dependency in Ember.js
Matthew Beale
 
PPTX
Effective C++/WinRT for UWP and Win32
Windows Developer
 
PDF
Testing Ember Apps: Managing Dependency
Matthew Beale
 
PDF
Building scalable applications with angular js
Andrew Alpert
 
PDF
The Road to Native Web Components
Mike North
 
PPTX
Good karma: UX Patterns and Unit Testing in Angular with Karma
ExoLeaders.com
 
PDF
Developing Modern Java Web Applications with Java EE 7 and AngularJS
Shekhar Gulati
 
PDF
Ember testing internals with ember cli
Cory Forsyth
 
PPTX
Full Stack Unit Testing
GlobalLogic Ukraine
 
PDF
Introduction to AngularJS For WordPress Developers
Caldera Labs
 
PDF
Future of Web Apps: Google Gears
dion
 
PPTX
Express JS
Designveloper
 
PDF
Redux vs Alt
Uldis Sturms
 
Workshop 14: AngularJS Parte III
Visual Engineering
 
Unit Testing Express and Koa Middleware in ES2015
Morris Singer
 
The JavaFX Ecosystem
Andres Almiray
 
Intro to testing Javascript with jasmine
Timothy Oxley
 
Workshop 12: AngularJS Parte I
Visual Engineering
 
Rapid prototyping and easy testing with ember cli mirage
Krzysztof Bialek
 
Building Progressive Web Apps for Windows devices
Windows Developer
 
Containers & Dependency in Ember.js
Matthew Beale
 
Effective C++/WinRT for UWP and Win32
Windows Developer
 
Testing Ember Apps: Managing Dependency
Matthew Beale
 
Building scalable applications with angular js
Andrew Alpert
 
The Road to Native Web Components
Mike North
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
ExoLeaders.com
 
Developing Modern Java Web Applications with Java EE 7 and AngularJS
Shekhar Gulati
 
Ember testing internals with ember cli
Cory Forsyth
 
Full Stack Unit Testing
GlobalLogic Ukraine
 
Introduction to AngularJS For WordPress Developers
Caldera Labs
 
Future of Web Apps: Google Gears
dion
 
Express JS
Designveloper
 
Redux vs Alt
Uldis Sturms
 
Ad

Viewers also liked (20)

PDF
Gui Input Tools for Math [UKMC09]
Greg TAPPERO
 
PDF
第一次用 Vue.js 就愛上 [改]
Kuro Hsu
 
PDF
Vue js 大型專案架構
Hina Chen
 
PPTX
Vue 2.0 + Vuex Router & Vuex at Vue.js
Takuya Tejima
 
ODP
An Introduction to Vuejs
Paddy Lock
 
PDF
VueJS: The Simple Revolution
Rafael Casuso Romate
 
PPTX
How tovuejs
Daniel Chou
 
PPTX
VueJS - Uma alternativa elegante
Jonathan Bijos
 
PDF
VueJs 簡介
Jocelyn Hsu
 
PPTX
Vuejs Angularjs e Reactjs. Veja as diferenças de cada framework!
José Barbosa
 
PDF
Agile Planning
Nikita Filippov
 
PPT
Эволюция Скрама в «Моём Круге»
Evgeny Kuryshev
 
PDF
VueJS meetup (Basics) @ nodum.io
Wietse Wind
 
PDF
Stop Making Excuses and Start Testing Your JavaScript
Ryan Anklam
 
PDF
nodum.io MongoDB Meetup (Dutch)
Wietse Wind
 
PDF
Automated Testing in EmberJS
Ben Limmer
 
PPTX
PHP 5.6 New and Deprecated Features
Mark Niebergall
 
PDF
действуй опираясь на ценности а не просто применяй инструменты максим цепков
Maxim Tsepkov
 
PDF
Advanced QUnit - Front-End JavaScript Unit Testing
Lars Thorup
 
PPTX
Qunit Java script Un
akanksha arora
 
Gui Input Tools for Math [UKMC09]
Greg TAPPERO
 
第一次用 Vue.js 就愛上 [改]
Kuro Hsu
 
Vue js 大型專案架構
Hina Chen
 
Vue 2.0 + Vuex Router & Vuex at Vue.js
Takuya Tejima
 
An Introduction to Vuejs
Paddy Lock
 
VueJS: The Simple Revolution
Rafael Casuso Romate
 
How tovuejs
Daniel Chou
 
VueJS - Uma alternativa elegante
Jonathan Bijos
 
VueJs 簡介
Jocelyn Hsu
 
Vuejs Angularjs e Reactjs. Veja as diferenças de cada framework!
José Barbosa
 
Agile Planning
Nikita Filippov
 
Эволюция Скрама в «Моём Круге»
Evgeny Kuryshev
 
VueJS meetup (Basics) @ nodum.io
Wietse Wind
 
Stop Making Excuses and Start Testing Your JavaScript
Ryan Anklam
 
nodum.io MongoDB Meetup (Dutch)
Wietse Wind
 
Automated Testing in EmberJS
Ben Limmer
 
PHP 5.6 New and Deprecated Features
Mark Niebergall
 
действуй опираясь на ценности а не просто применяй инструменты максим цепков
Maxim Tsepkov
 
Advanced QUnit - Front-End JavaScript Unit Testing
Lars Thorup
 
Qunit Java script Un
akanksha arora
 
Ad

Similar to Vuejs testing (20)

PDF
World-Class Testing Development Pipeline for Android
Pedro Vicente Gómez Sánchez
 
PDF
TDD: Develop, Refactor and Release With Confidence
Mehdi Valikhani
 
PDF
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
PDF
Don't let your tests slow you down
Daniel Irvine
 
PDF
How to test complex SaaS applications - The family july 2014
Guillaume POTIER
 
PDF
ES3-2020-06 Test Driven Development (TDD)
David Rodenas
 
PDF
One Deceptively Simple Question to Unlock Testability, Better Design, and TDD
Derek Lee
 
PDF
Factorio crack FREE Download Latest Version 2025
muhammadwaqaryounus6
 
PDF
Crack FREE Gta 5Download Latest Version 2025
waqarcracker5
 
PDF
Agile mobile
Godfrey Nolan
 
PDF
Functional Testing for React Native Apps
K. Matthew Dupree
 
PPTX
Contract testing: Beyond API functional testing
Gaurav Singh
 
PDF
What NOT to test in your project
alexandre freire
 
PPTX
Dev Day 2024: Jonathan Frere - Playwright: Das Beste aus dem Dramatiker herau...
emmaberlin1
 
PDF
5 levels of api test automation
ShekharRamphal
 
PPTX
Mocking - Visug session
Maarten Balliauw
 
PDF
TDD CrashCourse Part3: TDD Techniques
David Rodenas
 
PPTX
Test-Driven Design Insights@DevoxxBE 2023.pptx
Victor Rentea
 
PDF
Testing Java Code Effectively
Andres Almiray
 
PDF
Intro to JavaScript Testing
Ran Mizrahi
 
World-Class Testing Development Pipeline for Android
Pedro Vicente Gómez Sánchez
 
TDD: Develop, Refactor and Release With Confidence
Mehdi Valikhani
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Don't let your tests slow you down
Daniel Irvine
 
How to test complex SaaS applications - The family july 2014
Guillaume POTIER
 
ES3-2020-06 Test Driven Development (TDD)
David Rodenas
 
One Deceptively Simple Question to Unlock Testability, Better Design, and TDD
Derek Lee
 
Factorio crack FREE Download Latest Version 2025
muhammadwaqaryounus6
 
Crack FREE Gta 5Download Latest Version 2025
waqarcracker5
 
Agile mobile
Godfrey Nolan
 
Functional Testing for React Native Apps
K. Matthew Dupree
 
Contract testing: Beyond API functional testing
Gaurav Singh
 
What NOT to test in your project
alexandre freire
 
Dev Day 2024: Jonathan Frere - Playwright: Das Beste aus dem Dramatiker herau...
emmaberlin1
 
5 levels of api test automation
ShekharRamphal
 
Mocking - Visug session
Maarten Balliauw
 
TDD CrashCourse Part3: TDD Techniques
David Rodenas
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Victor Rentea
 
Testing Java Code Effectively
Andres Almiray
 
Intro to JavaScript Testing
Ran Mizrahi
 

Recently uploaded (20)

PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
PDF
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
PPTX
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
PDF
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
PPTX
Presentation about variables and constant.pptx
safalsingh810
 
PDF
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PDF
Micromaid: A simple Mermaid-like chart generator for Pharo
ESUG
 
PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
PDF
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
PPTX
Services offered by Dynamic Solutions in Pakistan
DaniyaalAdeemShibli1
 
PPTX
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
DOCX
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
PDF
Exploring AI Agents in Process Industries
amoreira6
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PDF
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
Presentation about variables and constant.pptx
safalsingh810
 
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
Micromaid: A simple Mermaid-like chart generator for Pharo
ESUG
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
Services offered by Dynamic Solutions in Pakistan
DaniyaalAdeemShibli1
 
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
Exploring AI Agents in Process Industries
amoreira6
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 

Vuejs testing

  • 2. Tooling. { "karma-mocha": "^0.2.1", "karma-chai": "^0.1.0", "karma-chai-as-promised": "^0.1.2", "karma-sinon": "^1.0.4", "karma-sinon-chai": "^1.2.0", "karma-sinon-stub-promise": "^1.0.0", "whatwg-fetch": "^0.11.0" "fetch-mock": "^4.1.0", }
  • 3. Testing a filter. import { prettybytes } from 'src/filters'; describe('Filter "prettybytes".', () => { it('Prettybytes shows the right KB, MB, GB, TB unit.', () => { expect(prettybytes(1024)).to.equal('1 KB'); expect(prettybytes(1048576)).to.equal('1 MB'); expect(prettybytes(1048576*1024)).to.equal('1 GB'); expect(prettybytes(1048576*1048576)).to.equal('1 TB'); expect(prettybytes(230)).to.equal('230 Bytes'); }); });
  • 4. Testing an API call, mocking fetch. import { authentify } from 'src/store/actions/auth'; import fetchMock from 'fetch-mock'; import { fetchUserToken } from 'src/api/web'; describe('Authentify action', () => { let sandbox; beforeEach(() => { sandbox = sinon.sandbox.create(); }); afterEach(() => { sandbox.restore(); fetchMock.restore(); }); it('FetchUserToken should eventually resolve with a token.', () => { fetchMock.mock('/login/getaccesstoken/', { Model: ' ' }); return fetchUserToken().should.eventually.equal(' '); }); });
  • 5. Testing a component (1/2). import Vue from 'vue'; import FinalCountdown from 'src/components/workflow/FinalCountdown'; describe('workflow/FinalCountDown component.', () => { const getComponent = (date) => { let vm = new Vue({ template: '<div><final-countdown v-ref:component :date="date"></final-countdown></div>', components: { FinalCountdown }, data: { date } }); return vm; }; ...
  • 6. Testing a component (2/2). it('Should render correctly with a date in the future.', () => { const tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000); const vm = getComponent(tomorrow).$mount(); expect(vm.$el).to.be.ok; // Counter should show 23:59:59 // timeUntilExpiration is a component method. expect(vm.$refs.component.timeUntilExpiration()).to.equal('23:59:59'); // Priority should be normal. expect(vm.$refs.component.priorityLevel()).to.equal('normal'); });
  • 7. Testing a component property change. it('Should be valid only when a radio option is selected.', () => { const vm = getComponent('Bob').$mount(); const component = vm.$refs.component; expect(component.isFormValid).to.be.false; component.picked = 3; component.$nextTick(() => { expect(component.isFormValid).to.be.true; }); });
  • 8. Testing a component event. it('Send should dispatch "declinedWorkflowTask" with the choice payload.', () => { const vm = getComponent('Bob').$mount(); const component = vm.$refs.component; let spy = sinon.spy(); vm.$on('declinedWorkflowTask', spy); component.sendReply(); expect(spy).to.have.been.calledWith({ choice: null, text: '' }); });
  • 9. Testing a component ready() hook. it('Should focus on textarea when ready.', (done) => { const vm = getComponent(); const component = vm.$refs.component; // Action triggered by Message Template child component. fetchMock.mock('/tutor/templates', [{ title: 'template A', body: 'AAA' }, { title: 'template B', body: 'BBB' }]); // Triggers ready() on our component. vm.$appendTo(document.body); component.$nextTick(() => { expect(document.activeElement).to.equal(component.$els.textarea); done(); }) });
  • 10. Testing with a Vuex store. import store from 'src/store'; describe('workflow/WorkflowAccept component.', () => { // Update store states here or import from fixtures. store.state.availability = { … }; const getComponent = () => { let vm = new Vue({ template: '<div><workflow-accept v-ref:component></workflow-accept></div>', components: { WorkflowAccept }, // Inject store here. store: store }); return vm.$mount(); };
  • 11. Testing a Vuex action (1/2). import { sendInitialDirectContactResponse } from 'src/store/actions/workflow'; import store from 'src/store'; const state = store.state; import { testAction } from './helper'; describe('sendInitialDirectContactResponse action.', () => { beforeEach(() => { state.workflow.workflowTask = { id: 1, conversationThread: { id: 2, }, initialDirectContact: { id: 3, }, }; ... });
  • 12. Testing a Vuex action (2/2). it('Should dispatch the right mutations.', (done) => { testAction(sendInitialDirectContactResponse, [1, 1, 'test'], state, [ { name: 'DELETE_WORKFLOW_TASK', payload: [1] }, { name: 'ADD_CONVERSATION_THREAD_TO_TOP' }, { name: 'UPDATE_CONVERSATION_THREAD' }, ], done); }); it('Should not dispatch ADD_CONVERSATION_THREAD_TO_TOP if ...', (done) => { state.app.menuSelection = 'archived'; testAction(sendInitialDirectContactResponse, [1, 1, 'test'], state, [ { name: 'DELETE_WORKFLOW_TASK', payload: [1] }, ], done); });
  • 13. Testing a Vuex action - testaction.js (1/2). // Helper for testing action with expected mutations. export function testAction(action, args, state, expectedMutations, done) { let count = 0; // mock dispatch const dispatch = (name, ...payload) => { const mutation = expectedMutations[count]; expect(mutation.name).to.equal(name); // if our mutation has a payload and our expected mutation // wants us to assert this payload. if (payload && mutation.payload) { expect(mutation.payload).to.deep.equal(payload); } count++; if (count === expectedMutations.length) { done(); }
  • 14. Testing a Vuex action - testaction.js (2/2) // ... if (count > expectedMutations.length) { // Missing non expected mutations. // List all expected mutations! expect(count).to.equal(expectedMutations.length); } } // call the action with mocked store and arguments action({ dispatch, state }, ...args); // check if no mutations should have been dispatched if (count === 0) { expect(expectedMutations.length).to.equal(0); done(); } };