Icon SunFilledIcon MoonStars

Icon LinkTesting with Jest

As noted in the testing intro , you are free to test your Sway and TS-SDK code with any JS framework available. Below we have an example of how to load and test a contract using Jest, but the general principles and steps are the same for any testing harness.

Here is a simple Sway program that takes an input and then returns it:

contract;
 
abi DemoContract {
fn return_input(input: u64) -> u64;
}
 
impl DemoContract for Contract {
fn return_input(input: u64) -> u64 {
	input
}
}

Here is JavaScript code testing the above program using a conventional Jest setup:

import { safeExec } from '@fuel-ts/errors/test-utils';
import { generateTestWallet } from '@fuel-ts/wallet/test-utils';
import { ContractFactory, Provider, toHex, BaseAssetId, Wallet, FUEL_NETWORK_URL } from 'fuels';
 
import storageSlots from '../contract/out/debug/demo-contract-storage_slots.json';
 
import { DemoContractAbi__factory } from './generated-types';
import bytecode from './generated-types/DemoContractAbi.hex';
 
describe('ExampleContract', () => {
	it('should return the input', async () => {
const provider = await Provider.create(FUEL_NETWORK_URL);
const wallet = await generateTestWallet(provider, [[1_000, BaseAssetId]]);
 
// Deploy
const factory = new ContractFactory(bytecode, DemoContractAbi__factory.abi, wallet);
const contract = await factory.deployContract();
 
// Call
const { value } = await contract.functions.return_input(1337).call();
 
// Assert
expect(value.toHex()).toEqual(toHex(1337));
 
// You can also make a call using the factory
const contractInstance = DemoContractAbi__factory.connect(contract.id, wallet);
const { value: v2 } = await contractInstance.functions.return_input(1337).call();
expect(v2.toHex()).toBe(toHex(1337));
	});
 
	it('deployContract method', async () => {
const provider = await Provider.create(FUEL_NETWORK_URL);
const wallet = await generateTestWallet(provider, [[1_000, BaseAssetId]]);
 
// Deploy
const contract = await DemoContractAbi__factory.deployContract(bytecode, wallet, {
	storageSlots,
});
 
// Call
const { value } = await contract.functions.return_input(1337).call();
 
// Assert
expect(value.toHex()).toEqual(toHex(1337));
	});
});

Was this page helpful?