Skip to content

Commit

Permalink
implemented delay behaviour
Browse files Browse the repository at this point in the history
  • Loading branch information
wheresrhys committed Oct 27, 2019
1 parent 2ba5cb6 commit 45fc743
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
9 changes: 9 additions & 0 deletions src/lib/compile-route.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,20 @@ const limitMatcher = route => {
route.reset = () => (timesLeft = route.repeat);
};

const delayResponse = (route) => {
const {delay} = route;
if (delay) {
const response = route.response;
route.response = new Promise(res => setTimeout(() => res(response), delay))
}
}

module.exports = route => {
validateRoute(route);
route = sanitizeRoute(route);
route.matcher = generateMatcher(route);
limitMatcher(route);
delayResponse(route)
return route;
};

Expand Down
25 changes: 21 additions & 4 deletions test/specs/responses.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -236,17 +236,17 @@ module.exports = fetchMock => {
});

it('function that returns a Promise', async () => {
fm.mock('http://it.at.there/', url => Promise.resolve('test'));
fm.mock('http://it.at.there/', url => Promise.resolve('test: ' + url));
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.status).to.equal(200);
expect(await res.text()).to.equal('test');
expect(await res.text()).to.equal('test: http://it.at.there/');
});

it('Promise for a function that returns a response', async () => {
fm.mock('http://it.at.there/', Promise.resolve(url => 'test'));
fm.mock('http://it.at.there/', Promise.resolve(url => 'test: ' + url));
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.status).to.equal(200);
expect(await res.text()).to.equal('test');
expect(await res.text()).to.equal('test: http://it.at.there/');
});

it('delay', async () => {
Expand All @@ -258,9 +258,26 @@ module.exports = fetchMock => {
expect(resolved).to.be.false;
await new Promise(res => setTimeout(res, 11))
expect(resolved).to.be.true;
const res = await req;
expect(res.status).to.equal(200);
});

it('delay a function response\'s execution', async () => {
const startTimestamp = new Date().getTime();
fm.mock('http://it.at.there/', () => ({timestamp: new Date().getTime()}), {delay: 20});
const req = fm.fetchHandler('http://it.at.there/');
let resolved = false;
req.then(() => resolved = true)
await new Promise(res => setTimeout(res, 10))
expect(resolved).to.be.false;
await new Promise(res => setTimeout(res, 11))
expect(resolved).to.be.true;
const res = await req;
expect(res.status).to.equal(200);
const responseTimestamp = (await res.json()).timestamp
expect(responseTimestamp - startTimestamp).to.be.within(20, 25);
});

it('Response', async () => {
fm.mock(
'http://it.at.there/',
Expand Down

0 comments on commit 45fc743

Please sign in to comment.