Add the deps to package.json
scripts:{
"serve": "vue-cli-service serve",
"dev": "run-p record serve", // run-p uses npm-run-all to run scripts in parallel, cross platform
"record": "polly listen -p 4244",
},
"devDependencies": {
"@pollyjs/adapter-fetch": "^2.4.0",
"@pollyjs/adapter-xhr": "^2.4.0",
"@pollyjs/cli": "^2.1.0",
"@pollyjs/core": "^2.4.0",
"@pollyjs/node-server": "^2.1.0",
"@pollyjs/persister-local-storage": "^2.1.0",
"@pollyjs/persister-rest": "^2.1.0",
"faker": "https://github.com/Marak/faker.js",
"npm-run-all": "^4.1.5",
}
Add this to main.js
const queryParams = new URLSearchParams(location.search);
if (process.env.NODE_ENV !== 'production' && queryParams.has('mock')) {
// @ts-ignore
import('@/mock');
}
Add src/mock/index.js
import { Polly } from '@pollyjs/core';
import XHRAdapter from '@pollyjs/adapter-xhr';
import FetchAdapter from '@pollyjs/adapter-fetch';
import RESTPersister from '@pollyjs/persister-rest';
import LocalStoragePersister from '@pollyjs/persister-local-storage';
var faker = window.Faker = require('faker');
Polly.register(FetchAdapter);
Polly.register(XHRAdapter);
Polly.register(LocalStoragePersister);
// Register the rest persister so its accessible by all future polly instances
Polly.register(RESTPersister);
Array.prototype.uniq = function (key) {
return key
? this.map(e => e[key])
.map((e, i, final) => final.indexOf(e) === i && i)
.filter(e => this[e])
.map(e => this[e])
: [...new Set(this)];
}
const polly = window.polly = new Polly('Main Recording', {
adapters: ['fetch', 'xhr'],
//persister: 'local-storage',
persister: 'rest',
logging: true, // Log requests to console
});
polly.configure({
mode: 'replay',
recordIfMissing: true,
persisterOptions: {
rest: {
host: 'http://localhost:4244'
}
}
});
const { server } = polly;
const API = path => process.env.VUE_APP_API_URL + '/' + path;
/*
Add a rule via the client-side server to intercept.
*/
server
.get(API`meetings`)
.intercept((req, res, interceptor) => {
// Wrap with Set to make sure that the values are unique. And we can use Array.from again to get the unique collection as array
/* const uniqueDates = Array.from(new Set(
// create an array of 50 future dates from future .1 years in the form of yyyy-mm-dd, may contain duplicates
(length =>
Array.from({length}, () => faker.unique(faker.date.future, [.1]).toISOString().substring(0, 10))
)(50)
)); */
if (req.query.type === 'counters') {
res.status(200).json(
(length => Array.from({ length }, () => ({
date: faker.unique(faker.date.future, [.2]).toISOString(), // date in .2 years from now
count: faker.random.number({ min: 1, max: 6 })
})))(10)
);
} else {
interceptor.abort();
}
});