Skip to content

Commit

Permalink
Add an example for asyncProperty
Browse files Browse the repository at this point in the history
Fixes #239
  • Loading branch information
dubzzz committed Nov 7, 2018
1 parent f71328d commit c5036f1
Show file tree
Hide file tree
Showing 5 changed files with 3,505 additions and 1 deletion.
26 changes: 26 additions & 0 deletions example/async-property/FakeApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export class FakeApi {
private static Users = ['toto', 'titi', 'tata', 'tutu'];

// Simulate a db query to fetch all users
// Can be replaced by any other asynchronous code
// This calls is supposed to fail whenever the query get back exactly zero result
static searchUsers(query: string): Promise<string[]> {
const answer = FakeApi.Users.filter(name => name.indexOf(query) !== -1);
return new Promise((resolve, reject) => {
if (answer.length === 0) {
setTimeout(() => reject('Unhandled exception'), 0);
return;
}
setTimeout(() => resolve(answer), 0);
});
}

// Simulate a call to a rest api
static findUser(username: string): Promise<{ id: number } | null> {
const id = FakeApi.Users.indexOf(username);
const answer = id !== -1 ? { id } : null;
return new Promise((resolve, reject) => {
setTimeout(() => resolve(answer), 0);
});
}
}
21 changes: 21 additions & 0 deletions example/async-property/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import * as fc from '../../lib/fast-check';
import { FakeApi } from './FakeApi';

describe('Asynchronous example', () => {
it('Search users asynchronously (fails)', async () => {
await fc.assert(
fc.asyncProperty(fc.string(), async query => {
const users = await FakeApi.searchUsers(query);
return Array.isArray(users) && users.every(name => name.indexOf(query) !== -1);
})
);
});
it('Get back user id from label (success)', async () => {
await fc.assert(
fc.asyncProperty(fc.constantFrom('toto', 'titi'), async username => {
const user = await FakeApi.findUser(username);
return user != null && typeof user.id === 'number' && user.id >= 0;
})
);
});
});
Loading

0 comments on commit c5036f1

Please sign in to comment.