Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix mock filename when running all specs #37

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cypress/integration/fixture.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ describe('setup', function () {
cy.readFile('../mocks/fixture.spec.json').should('not.exist');
cy.readFile('../fixtures/fixture-spec').should('not.exist');
// Ensure the http request has finished
cy.contains(/"userId":1/i);
cy.contains(/"id":1/i);
});
});

Expand Down
10 changes: 1 addition & 9 deletions cypress/integration/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,7 @@ <h1>cypress-autorecord</h1>
</div>
</main>
<script>
// var oReq = new XMLHttpRequest();
// oReq.addEventListener('load', function () {
// var json = JSON.parse(this.responseText);
// document.getElementById('json').innerText = JSON.stringify(json);
// });
// oReq.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
// oReq.send();

fetch('https://jsonplaceholder.typicode.com/todos/1')
fetch('https://reqres.in/api/users/1')
.then((response) => response.json())
.then((json) => {
document.getElementById('json').innerText = JSON.stringify(json);
Expand Down
17 changes: 14 additions & 3 deletions cypress/integration/spec.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
const autoRecord = require('../../index');
const testName = 'records a mock after the test has finished';

// Ensures the next test doesn't load fixtures before they're
// deleted!
describe('beforeSetup', function () {
beforeEach(function () {
cy.task('removeAllMocks');
});

it('deletes the mocks', function () {
cy.readFile('../mocks/spec.json').should('not.exist');
});
});

describe('setup', function () {
autoRecord();

beforeEach(function () {
cy.task('removeAllMocks');
cy.visit('cypress/integration/index.html');
});

it(testName, function () {
cy.readFile('../mocks/spec.json').should('not.exist');
// Ensure the http request has finished
cy.contains(/"userId":1/i);
cy.contains(/"id":1/i);
});
});

Expand All @@ -25,7 +36,7 @@ describe('test', function () {
const { routes } = mock[testName];
const [{ response }] = routes;

expect(response).to.include({ userId: 1, id: 1 });
expect(response.data).to.include({ id: 1 });
});
});
});
Expand Down
64 changes: 39 additions & 25 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,8 @@ const whitelistHeaders = cypressConfig.whitelistHeaders || [];
const maxInlineResponseSize = cypressConfig.maxInlineResponseSize || 70;
const supportedMethods = ['get', 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD'];

const fileName = path.basename(
Cypress.spec.name,
path.extname(Cypress.spec.name),
);
// The replace fixes Windows path handling
const fixturesFolder = Cypress.config('fixturesFolder').replace(/\\/g, '/');
const fixturesFolderSubDirectory = fileName.replace(/\./, '-');
const mocksFolder = path.join(fixturesFolder, '../mocks');

before(function() {
Expand Down Expand Up @@ -57,12 +52,16 @@ module.exports = function autoRecord() {

before(function() {
// Get mock data that relates to this spec file
const fileName = getFileName(this.currentTest);
cy.task('readFile', path.join(mocksFolder, `${fileName}.json`)).then((data) => {
routesByTestId = data === null ? {} : data;
});
});

beforeEach(function() {
const fileName = getFileName(this.currentTest);
const fixturesFolderSubDirectory = getFixturesSubFolder(fileName);

// Reset routes before each test case
routes = [];

Expand All @@ -76,13 +75,13 @@ module.exports = function autoRecord() {

req.reply((res) => {
const url = req.url;
const status = res.statusCode;
const method = req.method;
const body = req.body;
const status = res.statusCode;
const data =
res.body.constructor.name === 'Blob'
? blobToPlain(res.body)
: res.body;
const body = req.body;
const headers = Object.entries(res.headers)
.filter(([key]) =>
whitelistHeaderRegexes.some((regex) => regex.test(key)),
Expand Down Expand Up @@ -141,31 +140,29 @@ module.exports = function autoRecord() {

const createStubbedRoute = (method, url) => {
let index = 0;
const response = sortedRoutes[method][url][index];

cy.intercept(
{
url,
method,
},
(req) => {
req.reply((res) => {
const newResponse = sortedRoutes[method][url][index];

res.send(
newResponse.status,
newResponse.fixtureId
? {
fixture: `${fixturesFolderSubDirectory}/${newResponse.fixtureId}.json`,
}
: newResponse.response,
newResponse.headers,
);

if (sortedRoutes[method][url].length > index + 1) {
index++;
}
});
const newResponse = sortedRoutes[method][url][index];

const response = {
statusCode: newResponse.status,
body: newResponse.response,
fixture: newResponse.fixtureId
? `${fixturesFolderSubDirectory}/${newResponse.fixtureId}.json`
: undefined,
headers: newResponse.headers,
};

req.reply(response);

if (sortedRoutes[method][url].length > index + 1) {
index++;
}
},
);
};
Expand All @@ -191,6 +188,9 @@ module.exports = function autoRecord() {
});

afterEach(function() {
const fileName = getFileName(this.currentTest);
const fixturesFolderSubDirectory = getFixturesSubFolder(fileName);

// Check to see if the current test already has mock data or if forceRecord is on
if (
(!routesByTestId[this.currentTest.title]
Expand Down Expand Up @@ -246,6 +246,9 @@ module.exports = function autoRecord() {
});

after(function() {
const fileName = getFileName(this.currentTest);
const fixturesFolderSubDirectory = getFixturesSubFolder(fileName);

// Transfer used mock data to new object to be stored locally
if (isCleanMocks) {
Object.keys(routesByTestId).forEach((testName) => {
Expand All @@ -268,3 +271,14 @@ module.exports = function autoRecord() {
});
});
};

function getFileName(currentTest) {
return path.basename(
currentTest.invocationDetails.relativeFile,
path.extname(currentTest.invocationDetails.relativeFile),
);
}

function getFixturesSubFolder(mockFilename) {
return mockFilename.replace(/\./, '-');
}