Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ethereum event fixtures for js.
/**
* Fixture for a custom ethereum event with unique return values
*/
import {
random, finance, date, lorem,
} from 'faker';
import generateEvent from './event.fixture';
import { fromDecimal, fromDate } from 'dapp-utils';
const EVENT_NAME = 'TransferComplete';
/**
* Generate a fake TransferComplete event object.
*
* @param {object} [overrides] - Fields to override the generated default event values.
* @return {object} - TransferComplete event object.
*/
const generateCustomEvent = (overrides = {}) => {
// example return values you might have
const returnValue1 = finance.ethereumAddress();
const returnValue2 = fromDecimal(random.float(), 10);
const timestamp = fromDate(date.past());
// merge in the following order:
// 1. generic fields all events share
// 2. unique to your custom event (mainly return values and `event` name)
// 3. provided overrides (allowing us to test expected values)
return {
...generateEvent(),
event: EVENT_NAME,
returnValues: {
0: returnValue1,
1: returnValue2,
2: timestamp,
returnValue1,
returnValue2,
timestamp,
},
...overrides,
};
};
export default generateCustomEvent;

To install a relatively recent version of Faker you'll need to install from a commit. The maintainer is still active and merging new features, but does not cut new releases.

npm install --save-dev faker@Marak/faker.js#<commit-sha>

I.e. npm install --save-dev faker@Marak/faker.js#d3ce6f1 (latest commit at the time of writing).

import { random, finance } from 'faker';
/**
* Mock an ethereum event object, minus return values unique to specific event types.
*/
const generateEvent = () => ({
address: finance.ethereumAddress(),
blockNumber: random.number(20000),
transactionHash: random.hexaDecimal(64),
transactionIndex: 0,
blockHash: random.hexaDecimal(64),
logIndex: 0,
removed: random.boolean(),
id: `log_${random.hexaDecimal(8)}`,
signature: random.hexaDecimal(64),
raw: {
data: random.hexaDecimal(1000),
topics: [random.hexaDecimal(64)],
},
});
export default generateEvent;
import generateCustomEvent from './fixtures/custom.fixture.js';
describe('CustomEvent', () => {
it('should ...', () => {
const event = generateCustomEvent();
// ...
});
it('should ...', () => {
const event = generateCustomEvent({
returnValues: {
returnValue1: 'foo bar',
},
});
// ...
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.