Skip to content

Commit

Permalink
Merge pull request #30 from percy/fetch
Browse files Browse the repository at this point in the history
Allow 10 seconds for stories to be set on window.
  • Loading branch information
timhaines authored Mar 12, 2018
2 parents 02d6498 + f3eb31c commit bf1d5df
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 7 deletions.
11 changes: 11 additions & 0 deletions packages/percy-storybook/src/__tests__/getStories-tests.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import getStories from '../getStories';
import { storiesKey } from '../constants';

let originalTimeout = 0;

beforeEach(function() {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 12000;
});

afterEach(function() {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
});

it('raises an error when called with an empty object', async () => {
try {
await getStories();
Expand Down
30 changes: 23 additions & 7 deletions packages/percy-storybook/src/getStories.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,29 @@ function getStoriesFromDom(previewJavascriptCode, options) {
src: [workerMock, localStorageMock, matchMediaMock, previewJavascriptCode],
done: (err, window) => {
if (err) return reject(err.response.body);
if (!window || !window[storiesKey]) {
const message =
'Storybook object not found on window. ' +
"Check your call to serializeStories in your Storybook's config.js.";
reject(new Error(message));
}
resolve(window[storiesKey]);
if (!window) return reject(new Error('Window not found when looking for stories.'));

// Check if the window has stories every 100ms for up to 10 seconds.
// This allows 10 seconds for any async pre-tasks (like fetch) to complete.
// Usually stories will be found on the first loop.
var checkStories = function(timesCalled) {
if (window[storiesKey]) {
// Found the stories, return them.
resolve(window[storiesKey]);
} else if (timesCalled < 100) {
// Stories not found yet, try again 100ms from now
setTimeout(() => {
checkStories(timesCalled + 1);
}, 100);
} else {
// Attempted 100 times, give up.
const message =
'Storybook object not found on window. ' +
"Check your call to serializeStories in your Storybook's config.js.";
reject(new Error(message));
}
};
checkStories(0);
},
};
if (options.debug) {
Expand Down

0 comments on commit bf1d5df

Please sign in to comment.