JS Testing API Reference

⚠️ Required: Your project must follow the required structure and it must be initialized to use the following functions.

Accounts

getAccountAddress

Resolves name alias to a Flow address (0x prefixed) under the following conditions:

  • If an account with a specific name has not been previously accessed, the framework will create a new one and then store it under the provided alias.
  • Next time when you call this method, it will grab exactly the same account. This allows you to create several accounts up-front and then use them throughout your code, without worrying that accounts match or trying to store and manage specific addresses.

Arguments

NameTypeDescription
aliasstringThe alias to reference or create.

Returns

TypeDescription
Address0x prefixed address of aliased account

Usage

1
import {getAccountAddress} from "@onflow/flow-js-testing"
2
3
const main = async () => {
4
const Alice = await getAccountAddress("Alice")
5
console.log({Alice})
6
}
7
8
main()

createAccount({name, keys})

In some cases, you may wish to manually create an account with a particular set of private keys

Options

Pass in the following as a single object with the following keys.

KeyTypeRequiredDescription
namestringNohuman-readable name to be associated with created account (will be used for address lookup within getAccountAddress)
keys[KeyObject or PublicKey]NoAn array of KeyObjects or PublicKeys to be added to the account upon creation (defaults to the universal private key)

📣 if name field not provided, the account address will not be cached and you will be unable to look it up using getAccountAddress.

Returns

TypeDescription
Address0x prefixed address of created account

Contracts

deployContractByName(props)

Deploys contract code located inside a Cadence file. Returns the transaction result.

Arguments

Props object accepts the following fields:

NameTypeOptionalDescription
namestringname of the file in contracts folder (with .cdc extension) and name of the contract (please note those should be the same)
toAddress(optional) account address, where contract will be deployed. If this is not specified, framework will create new account with randomized alias.
addressMapAddressMap(optional) object to use for address mapping of existing deployed contracts
args[Any](optional) arguments, which will be passed to contract initializer. (optional) if template does not expect any arguments.
updateboolean(optional) whether to update deployed contract. Default: false
transformers[CadenceTransformer](optional) an array of operators to modify the code, before submitting it to network

Returns

TypeDescription
ResponseObjectResult of the deploying transaction.

Usage

1
import path from "path";
2
import { init, emulator, deployContractByName } from "@onflow/flow-js-testing";
3
4
const main = async () => {
5
const basePath = path.resolve(__dirname, "../cadence");
6
7
await init(basePath);
8
await emulator.start();
9
10
// We will deploy our contract to the address that corresponds to "Alice" alias
11
const to = await getAccountAddress("Alice");
12
13
// We assume there is a file on "../cadence/contracts/Wallet.cdc" path
14
const name = "Wallet";
15
16
// Arguments will be processed and type matched in the same order as they are specified
17
// inside of a contract template
18
const args = [1337, "Hello", { name: "Alice" }];
19
20
const [deploymentResult, err] = await deployContractByName({ to, name });
21
console.log({ deploymentResult }, { err });
22
}
23
24
await emulator.stop();
25
};
26
27
main();

In a bit more rare case you would want to deploy contract code not from existing template file, but rather from string representation of it. deployContract method will help you achieve this.

deployContract(props)

Deploys contract code specified as string. Returns the transaction result.

Arguments

Props object accepts the following fields:

NameTypeOptionalDescription
contractCodestringstring representation of contract
namestringname of the contract to be deployed. Should be the same as the name of the contract provided in contractCode
toAddressaccount address, where contract will be deployed. If this is not specified, framework will create new account with randomized alias.
addressMapAddressMapobject to use for import resolver. Default: {}
args[Any]arguments, which will be passed to contract initializer. Default: []
updatebooleanwhether to update deployed contract. Default: false
transformers[CadenceTransformer]an array of operators to modify the code, before submitting it to network

Returns

TypeDescription
ResponseObjectResult of the deploying transaction.

Usage

1
import path from "path"
2
import {
3
init,
4
emulator,
5
getAccountAddress,
6
deployContract,
7
executeScript,
8
} from "@onflow/flow-js-testing"
9
;(async () => {
10
const basePath = path.resolve(__dirname, "../cadence")
11
12
await init(basePath)
13
await emulator.start()
14
15
// We can specify, which account will hold the contract
16
const to = await getAccountAddress("Alice")
17
18
const name = "Wallet"
19
const code = `
20
pub contract Wallet{
21
pub let balance: UInt
22
init(balance: UInt){
23
self.balance = balance
24
}
25
}
26
`
27
const args = [1337]
28
29
await deployContract({to, name, code, args})
30
31
const [balance, err] = await executeScript({
32
code: `
33
import Wallet from 0x01
34
pub fun main(): UInt{
35
return Wallet.balance
36
}
37
`,
38
})
39
console.log({balance}, {err})
40
41
await emulator.stop()
42
})()

While framework have automatic import resolver for Contracts you might want to know where it's currently deployed. We provide a method getContractAddress for this.

getContractAddress(name)

Returns address of the account where the contract is currently deployed.

Arguments

NameTypeDescription
namestringname of the contract

Returns

TypeDescription
Address0x prefixed address

Usage

1
import path from "path"
2
import {init, emulator, deployContractByName, getContractAddress} from "../src"
3
;(async () => {
4
const basePath = path.resolve(__dirname, "./cadence")
5
6
await init(basePath)
7
await emulator.start()
8
9
// if we omit "to" it will be deployed to Service Account
10
// but let's pretend we don't know where it will be deployed :)
11
await deployContractByName({name: "Hello"})
12
13
const contractAddress = await getContractAddress("Hello")
14
console.log({contractAddress})
15
16
await emulator.stop()
17
})()

📣 Framework does not support contracts with identical names deployed to different accounts. While you can deploy contract to a new address, the internal system, which tracks where contracts are deployed, will only store last address.

Cryptography

pubFlowKey(keyObject)

The pubFlowKey method exported by Flow JS Testing Library will generate an RLP-encoded public key given a private key, hashing algorithm, signing algorithm, and key weight.

NameTypeOptionalDescription
keyObjectKeyObjectan object containing a private key & the key's hashing/signing information

If keyObject is not provided, Flow JS Testing will default to the universal private key.

Returns

TypeDescription
BufferRLP-encoded public key

Usage

1
import {pubFlowKey}
2
3
const key = {
4
privateKey: "a1b2c3" // private key as hex string
5
hashAlgorithm: HashAlgorithm.SHA3_256
6
signatureAlgorithm: SignatureAlgorithm.ECDSA_P256
7
weight: 1000
8
}
9
10
const pubKey = await pubFlowKey(key) // public key generated from keyObject provided
11
const genericPubKey = await pubFlowKey() // public key generated from universal private key/service key

signUserMessage(msgHex, signer, domainTag)

The signUserMessage method will produce a user signature of some arbitrary data using a particular signer.

Arguments

NameTypeOptionalDescription
msgHexstring or Buffera hex-encoded string or Buffer which will be used to generate the signature
signerAddress or SignerInfoAddress or SignerInfo object representing user to generate this signature for (default: universal private key)
domainTagstringDomain separation tag provided as a utf-8 encoded string (default: no domain separation tag). See more about domain tags here.

Returns

TypeDescription
SignatureObjectAn object representing the signature for the message & account/keyId which signed for this message

Usage

1
import {signUserMessage, getAccountAddress} from "@onflow/flow-js-testing"
2
3
const Alice = await getAccountAddress("Alice")
4
const msgHex = "a1b2c3"
5
6
const signature = await generateUserSignature(msgHex, Alice)

verifyUserSigntatures(msgHex, signatures, domainTag)

Used to verify signatures generated by signUserMessage. This function takes an array of signatures and verifies that the total key weight sums to >= 1000 and that these signatures are valid.

Arguments

NameTypeOptionalDescription
msgHexstringthe message which the provided signatures correspond to provided as a hex-encoded string or Buffer
signatures[SignatureObject]An array of SignatureObjects which will be verified against this message
domainTagstringDomain separation tag provided as a utf-8 encoded string (default: no domain separation tag). See more about domain tags here.

Returns

This method returns an object with the following keys:

TypeDescription
booleanReturns true if signatures are valid and total weight >= 1000

Usage

1
import {
2
signUserMessage,
3
verifyUserSignatures,
4
getAccountAddress,
5
} from "@onflow/flow-js-testing"
6
7
const Alice = await getAccountAddress("Alice")
8
const msgHex = "a1b2c3"
9
10
const signature = await generateUserSignature(msgHex, Alice)
11
12
console.log(await verifyUserSignatures(msgHex, Alice)) // true
13
14
const Bob = await getAccountAddress("Bob")
15
console.log(await verifyUserSignatures(msgHex, Bob)) // false

Emulator

Flow Javascript Testing Framework exposes emulator singleton allowing you to run and stop emulator instance programmatically. There are two methods available on it.

emulator.start(options)

Starts emulator on a specified port. Returns Promise.

Arguments

NameTypeOptionalDescription
optionsEmulatorOptionsan object containing options for starting the emulator

EmulatorOptions

KeyTypeOptionalDescription
loggingbooleanwhether log messages from emulator shall be added to the output (default: false)
flagsstringcustom command-line flags to supply to the emulator (default: no flags)
adminPortnumberoverride the port which the emulator will run the admin server on (default: auto)
restPortnumberoverride the port which the emulator will run the REST server on (default: auto)
grpcPortnumberoverride the port which the emulator will run the GRPC server on (default: auto)

Returns

TypeDescription
PromisePromise, which resolves to true if emulator started successfully

Usage

1
import path from "path"
2
import {emulator, init} from "../src"
3
;(async () => {
4
const basePath = path.resolve(__dirname, "../cadence")
5
6
await init(basePath)
7
8
// Start emulator instance on port 8080
9
await emulator.start()
10
console.log("emulator is working")
11
12
// Stop running emulator
13
await emulator.stop()
14
console.log("emulator has been stopped")
15
})()

emulator.stop()

Stops emulator instance. Returns Promise.

Arguments

This method does not expect any arguments.

Returns

TypeDescription
PromisePromise, which resolves to true if emulator stopped without issues

Usage

1
import {emulator, init} from "@onflow/flow-js-testing"
2
3
describe("test setup", () => {
4
// Instantiate emulator and path to Cadence files
5
beforeEach(async () => {
6
const basePath = path.resolve(__dirname, "../cadence")
7
8
await init(basePath)
9
await emulator.start()
10
})
11
12
// Stop emulator, so it could be restarted
13
afterEach(async () => {
14
await emulator.stop()
15
})
16
})

emulator.setLogging(newState)

Set logging flag on emulator, allowing to temporally enable/disable logging.

Arguments

NameTypeDescription
newStatebooleanEnable/disable logging

Returns

Method does not return anything.

Usage

1
import path from "path"
2
import {emulator, init} from "@onflow/flow-js-testing"
3
4
describe("test setup", () => {
5
// Instantiate emulator and path to Cadence files
6
beforeEach(async () => {
7
const basePath = path.resolve(__dirname, "../cadence")
8
9
await init(basePath)
10
await emulator.start()
11
})
12
13
// Stop emulator, so it could be restarted
14
afterEach(async () => {
15
await emulator.stop()
16
})
17
18
test("basic test", async () => {
19
// Turn on logging from begining
20
emulator.setLogging(true)
21
// some asserts and interactions
22
23
// Turn off logging for later calls
24
emulator.setLogging(false)
25
// more asserts and interactions here
26
})
27
})

FLOW Management

Some actions on the network will require account to have certain amount of FLOW token - transaction and storage fees, account creation, etc.

Framework provides a method to query balance with getFlowBalance and mint new tokens via mintFlow. You can find information how to use them below.

getFlowBalance(address)

Fetch current FlowToken balance of account specified by address

Arguments

NameTypeDescription
addressAddressaddress of the account to check

Returns

TypeDescription
stringUFix64 amount of FLOW tokens stored in account storage represented as string

Usage

1
import {
2
init,
3
emulator,
4
getAccountAddress,
5
getFlowBalance,
6
} from "@onflow/flow-js-testing"
7
8
const main = async () => {
9
const basePath = path.resolve(__dirname, "../cadence")
10
11
await init(basePath)
12
await emulator.start()
13
14
const Alice = await getAccountAddress("Alice")
15
16
const [result, error] = await getFlowBalance(Alice)
17
console.log({result}, {error})
18
19
await emulator.stop()
20
}
21
22
main()

mintFlow(recipient, amount)

Sends transaction to mint specified amount of FLOW token and send it to recipient.

⚠️ Required: Framework shall be initialized with init method for this method to work.

Arguments

NameTypeDescription
recipientAddressaddress of the account to check
amountstringUFix64 amount of FLOW tokens to mint and send to recipient

Returns

TypeDescription
ResponseObjectTransaction result

Usage

1
import path from "path"
2
import {
3
init,
4
emulator,
5
getAccountAddress,
6
getFlowBalance,
7
mintFlow,
8
} from "../src"
9
;(async () => {
10
const basePath = path.resolve(__dirname, "./cadence")
11
12
await init(basePath)
13
await emulator.start()
14
15
// Get address for account with alias "Alice"
16
const Alice = await getAccountAddress("Alice")
17
18
// Get initial balance
19
const [initialBalance] = await getFlowBalance(Alice)
20
console.log(initialBalance)
21
22
// Add 1.0 FLOW tokens to Alice account
23
await mintFlow(Alice, "1.0")
24
25
// Check updated balance
26
const updatedBalance = await getFlowBalance(Alice)
27
console.log({updatedBalance})
28
29
await emulator.stop()
30
})()

Init

For Framework to operate properly you need to initialize it first. You can do it with provided init method.

init( basePath, options)

Initializes framework variables.

Arguments

NameTypeOptionalDescription
bastPathstringpath to the folder holding all Cadence template files
optionsobjectoptions object to use during initialization

Options

NameTypeOptionalDescription
pkeyprivate key for service account

Returns

TypeDescription
PromisePromise, which resolves to true if framework was initialized properly

Usage

1
import path from "path"
2
import {init} from "@onflow/flow-js-testing"
3
4
describe("test setup", () => {
5
beforeEach(async () => {
6
const basePath = path.resolve(__dirname, "../cadence")
7
await init(basePath)
8
9
// alternatively you can pass specific port
10
// await init(basePath, {port: 8085})
11
})
12
})

Environment

getBlockOffset()

Returns current block offset - amount of blocks added on top of real current block height.

Returns

TypeDescription
stringnumber representing amount of blocks added on top of real current block (encoded as string)

Usage

1
import path from "path"
2
import {init, emulator, getBlockOffset} from "@onflow/flow-js-testing"
3
4
const main = async () => {
5
const basePath = path.resolve(__dirname, "../cadence")
6
7
init(basePath)
8
await emulator.start()
9
10
const [blockOffset, err] = await getBlockOffset()
11
console.log({blockOffset}, {err})
12
13
await emulator.stop()
14
}
15
16
main()

setBlockOffset(offset)

Returns current block offset - amount of blocks added on top of real current block height.

Arguments

NameTypeDescription

Returns

TypeDescription
numbernumber representing amount of blocks added on top of real current block height

Usage

1
import path from "path"
2
import {
3
init,
4
emulator,
5
executeScript,
6
getBlockOffset,
7
setBlockOffset,
8
sendTransaction,
9
} from "@onflow/flow-js-testing"
10
11
const main = async () => {
12
const basePath = path.resolve(__dirname, "../cadence")
13
14
init(basePath)
15
await emulator.start()
16
17
// Offset current block height by 42
18
await setBlockOffset(42)
19
20
const [blockOffset, err] = await getBlockOffset()
21
console.log({blockOffset}, {err})
22
23
// "getCurrentBlock().height" in your Cadence code will be replaced by Manager to a mocked value
24
const code = `
25
pub fun main(): UInt64 {
26
return getCurrentBlock().height
27
}
28
`
29
30
const [result, error] = await executeScript({code})
31
console.log({result}, {error})
32
33
await emulator.stop()
34
}
35
36
main()

getTimestampOffset()

Returns current timestamp offset - amount of seconds added on top of real current timestamp.

Returns

TypeDescription
numbernumber representing amount of seconds added on top of real current timestamp

Usage

1
import path from "path"
2
import {init, emulator, getTimestampOffset} from "@onflow/flow-js-testing"
3
4
const main = async () => {
5
const basePath = path.resolve(__dirname, "../cadence")
6
7
init(basePath)
8
await emulator.start()
9
10
const [timestampOffset, err] = await getTimestampOffset()
11
console.log({timestampOffset}, {err})
12
13
await emulator.stop()
14
}
15
16
main()

setTimestampOffset(offset)

Returns current timestamp offset - amount of seconds added on top of real current timestamp.

Arguments

NameTypeDescription

Returns

TypeDescription
numbernumber representing amount of seconds added on top of real current timestamp

Usage

1
import path from "path"
2
import {
3
init,
4
emulator,
5
executeScript,
6
getTimestampOffset,
7
setTimestampOffset,
8
sendTransaction,
9
} from "@onflow/flow-js-testing"
10
11
const main = async () => {
12
const basePath = path.resolve(__dirname, "../cadence")
13
14
init(basePath)
15
await emulator.start()
16
17
// Offset current timestamp by 10s
18
await setTimestampOffset(10)
19
20
const [timestampOffset, err] = await getTimestampOffset()
21
console.log({timestampOffset}, {err})
22
23
// "getCurrentBlock().timestamp" in your Cadence code will be replaced by Manager to a mocked value
24
const code = `
25
pub fun main(): UInt64 {
26
return getCurrentBlock().timestamp
27
}
28
`
29
30
const [result, error] = await executeScript({code})
31
console.log({result}, {error})
32
33
await emulator.stop()
34
}
35
36
main()

Jest Helpers

In order to simplify the process even further we've created several Jest-based methods, which will help you to catch thrown errors and ensure your code works as intended.

shallPass(ix)

Ensure transaction does not throw and sealed.

Arguments

NameTypeDescription
ixInteractioninteraction, either in form of a Promise or function

Returns

TypeDescription
ResponseObjectTransaction result

Usage

1
import path from "path"
2
import {
3
init,
4
emulator,
5
shallPass,
6
sendTransaction,
7
getAccountAddress,
8
} from "js-testing-framework"
9
10
// We need to set timeout for a higher number, cause some interactions might need more time
11
jest.setTimeout(10000)
12
13
describe("interactions - sendTransaction", () => {
14
// Instantiate emulator and path to Cadence files
15
beforeEach(async () => {
16
const basePath = path.resolve(__dirname, "./cadence")
17
await init(basePath)
18
return emulator.start()
19
})
20
21
// Stop emulator, so it could be restarted
22
afterEach(async () => {
23
return emulator.stop()
24
})
25
26
test("basic transaction", async () => {
27
const code = `
28
transaction(message: String){
29
prepare(singer: AuthAccount){
30
log(message)
31
}
32
}
33
`
34
const Alice = await getAccountAddress("Alice")
35
const signers = [Alice]
36
const args = ["Hello, Cadence"]
37
38
const [txResult, error] = await shallPass(
39
sendTransaction({
40
code,
41
signers,
42
args,
43
})
44
)
45
46
// Transaction result will hold status, events and error message
47
console.log({txResult}, {error})
48
})
49
})

shallRevert(ix, message)

Ensure interaction throws an error. Can test for specific error messages or catch any error message if message is not provided. Returns Promise, which contains result, when resolved.

Arguments

NameTypeDescription
ixInteractiontransaction, either in form of a Promise or function
message (optional)string or RegExpexpected error message provided as either a string equality or regular expression to match, matches any error by default

Returns

TypeDescription
ResponseObjectTransaction result

Usage

1
import path from "path"
2
import {
3
init,
4
emulator,
5
shallPass,
6
sendTransaction,
7
getAccountAddress,
8
} from "js-testing-framework"
9
10
// We need to set timeout for a higher number, cause some interactions might need more time
11
jest.setTimeout(10000)
12
13
describe("interactions - sendTransaction", () => {
14
// Instantiate emulator and path to Cadence files
15
beforeEach(async () => {
16
const basePath = path.resolve(__dirname, "./cadence")
17
await init(basePath)
18
return emulator.start()
19
})
20
21
// Stop emulator, so it could be restarted
22
afterEach(async () => {
23
return emulator.stop()
24
})
25
26
test("basic transaction", async () => {
27
const code = `
28
transaction(message: String){
29
prepare(singer: AuthAccount){
30
panic("You shall not pass!")
31
}
32
}
33
`
34
const Alice = await getAccountAddress("Alice")
35
const signers = [Alice]
36
const args = ["Hello, Cadence"]
37
38
// Catch any cadence error
39
let [txResult, error] = await shallRevert(
40
sendTransaction({
41
code,
42
signers,
43
args,
44
})
45
)
46
47
// Catch only specific panic message
48
let [txResult, error] = await shallRevert(
49
sendTransaction({
50
code,
51
signers,
52
args,
53
}),
54
"You shall not pass!"
55
)
56
57
// Transaction result will hold status, events and error message
58
console.log({txResult}, {error})
59
})
60
})

shallResolve(ix)

Ensure interaction resolves without throwing errors.

Arguments

NameTypeDescription
ixInteractioninteraction, either in form of a Promise or function

Returns

TypeDescription
InteractionResultInteraction result

Usage

1
import path from "path"
2
import {init, emulator, shallPass, executeScript} from "js-testing-framework"
3
4
// We need to set timeout for a higher number, cause some interactions might need more time
5
jest.setTimeout(10000)
6
7
describe("interactions - sendTransaction", () => {
8
// Instantiate emulator and path to Cadence files
9
beforeEach(async () => {
10
const basePath = path.resolve(__dirname, "./cadence")
11
await init(basePath)
12
return emulator.start()
13
})
14
15
// Stop emulator, so it could be restarted
16
afterEach(async () => {
17
return emulator.stop()
18
})
19
20
test("basic script", async () => {
21
const code = `
22
pub fun main():Int{
23
return 42
24
}
25
`
26
27
const [result, error] = await shallResolve(
28
executeScript({
29
code,
30
})
31
)
32
33
expect(result).toBe(42)
34
expect(error).toBe(null)
35
})
36
})

Scripts

It is often the case that you need to query current state of the network. For example, to check balance of the account, read public value of the contract or ensure that user has specific resource in their storage.

We abstract this interaction into single method called executeScript. Method have 2 different signatures.

⚠️ Required: Your project must follow the required structure it must be initialized to use the following functions.

executeScript(props)

Provides explicit control over how you pass values.

Arguments

props object accepts following fields:

NameTypeOptionalDescription
codestringstring representation of Cadence script
namestringname of the file in scripts folder to use (sans .cdc extension)
args[any]an array of arguments to pass to script. Optional if script does not expect any arguments.
transformers[CadenceTransformer]an array of operators to modify the code, before submitting it to network

⚠️ Required: Either code or name field shall be specified. Method will throw an error if both of them are empty. If name field provided, framework will source code from file and override value passed via code field.

Returns

TypeDescription
ResponseObjectScript result

Usage

1
import path from "path"
2
import {init, emulator, executeScript} from "@onflow/flow-js-testing"
3
4
const main = async () => {
5
const basePath = path.resolve(__dirname, "../cadence")
6
7
// Init framework
8
init(basePath)
9
// Start emulator
10
await emulator.start()
11
12
// Define code and arguments we want to pass
13
const code = `
14
pub fun main(message: String): Int{
15
log(message)
16
17
return 42
18
}
19
`
20
const args = ["Hello, from Cadence"]
21
22
const [result, error, logs] = await executeScript({code, args})
23
console.log({result}, {error}, {logs})
24
25
// Stop emulator instance
26
await emulator.stop()
27
}
28
29
main()

executeScript(name: string, args: [any])

This signature provides simplified way of executing a script, since most of the time you will utilize existing Cadence files.

Arguments

NameTypeOptionalDescription
namestringname of the file in scripts folder to use (sans .cdc extension)
args[any]an array of arguments to pass to script. Optional if scripts don't expect any arguments. Default: []

Returns

TypeDescription
ResponseObjectScript result

Usage

1
import path from "path"
2
import {init, emulator, executeScript} from "@onflow/flow-js-testing"
3
4
const main = async () => {
5
const basePath = path.resolve(__dirname, "../cadence")
6
7
// Init framework
8
init(basePath)
9
// Start emulator
10
await emulator.start()
11
12
// Define arguments we want to pass
13
const args = ["Hello, from Cadence"]
14
15
// We assume there is a file `scripts/log-message.cdc` under base path
16
const [result, error, logs] = await executeScript("log-message", args)
17
console.log({result}, {error}, {logs})
18
19
await emulator.stop()
20
}
21
22
main()

Transactions

Another common case is interactions that mutate network state - sending tokens from one account to another, minting new NFT, etc. Framework provides sendTransaction method to achieve this. This method have 2 different signatures.

⚠️ Required: Your project must follow the required structure it must be initialized to use the following functions.

sendTransaction(props)

Send transaction to network. Provides explicit control over how you pass values.

Arguments

props object accepts following fields:

NameTypeOptionalDescription
codestringstring representation of Cadence transaction
namestringname of the file in transaction folder to use (sans .cdc extension)
args[any]an array of arguments to pass to transaction. Optional if transaction does not expect any arguments.
signers[Address or SignerInfo]an array of Address or SignerInfo objects representing transaction autorizers
addressMapAddressMapname/address map to use as lookup table for addresses in import statements
transformers[CadenceTransformer]an array of operators to modify the code, before submitting it to network

⚠️ Required: Either code or name field shall be specified. Method will throw an error if both of them are empty. If name field provided, framework will source code from file and override value passed via code field.

📣 if signers field not provided, service account will be used to authorize the transaction.

📣 Pass addressMap only in cases, when you would want to override deployed contract. Otherwide imports can be resolved automatically without explicitly passing them via addressMap field

Usage

1
import path from "path"
2
import {
3
init,
4
emulator,
5
sendTransaction,
6
getAccountAddress,
7
} from "@onflow/flow-js-testing"
8
9
const main = async () => {
10
const basePath = path.resolve(__dirname, "../cadence")
11
12
// Init framework
13
await init(basePath)
14
// Start emulator
15
await emulator.start()
16
17
// Define code and arguments we want to pass
18
const code = `
19
transaction(message: String){
20
prepare(signer: AuthAccount){
21
log(message)
22
}
23
}
24
`
25
const args = ["Hello, from Cadence"]
26
const Alice = await getAccountAddress("Alice")
27
const signers = [Alice]
28
29
const [result, error, logs] = await sendTransaction({code, args, signers})
30
console.log({result}, {error}, {logs})
31
32
// Stop emulator instance
33
await emulator.stop()
34
}
35
36
main()

sendTransaction(name, signers, args)

This signature provides simplified way to send a transaction, since most of the time you will utilize existing Cadence files.

NameTypeOptionalDescription
namestringname of the file in transaction folder to use (sans .cdc extension)
args[any]an array of arguments to pass to transaction. Optional if transaction does not expect any arguments.
signers[Address or SignerInfoObject]an array of Address or array of SignerInfoObject representing transaction autorizers

Usage

1
import path from "path"
2
import {
3
init,
4
emulator,
5
sendTransaction,
6
shallPass,
7
} from "@onflow/flow-js-testing"
8
9
const main = async () => {
10
const basePath = path.resolve(__dirname, "../cadence")
11
12
// Init framework
13
await init(basePath)
14
// Start emulator
15
await emulator.start()
16
17
// Define arguments we want to pass
18
const args = ["Hello, Cadence"]
19
20
const [result, error, logs] = await shallPass(
21
sendTransaction("log-message", [], args)
22
)
23
console.log({result}, {error}, {logs})
24
25
// Stop the emulator instance
26
await emulator.stop()
27
}
28
29
main()

Templates

The philosophy behind Flow JS Testing Framework is to be a set of helper methods. They can be used in opinionated way, envisioned by Flow Team. Or they can work as building blocks, allowing developers to build their own testing solution as they see fit.

Following methods used inside other framework methods, but we feel encouraged to list them here as well.

getTemplate(file, addressMap, byAddress)

Returns Cadence template as string with addresses replaced using addressMap

NameTypeOptionalDescription
filestringrelative (to the place from where the script was called) or absolute path to the file containing the code
addressMapAddressMapobject to use for address mapping of existing deployed contracts. Default: {}
byAddressbooleanwhether addressMap is {name:address} or {address:address} type. Default: false

Returns

TypeDescription
stringcontent of a specified file

Usage

1
import path from "path"
2
import {init, getTemplate} from "@onflow/flow-js-testing"
3
4
const main = async () => {
5
const basePath = path.resolve(__dirname, "../cadence")
6
await init(basePath)
7
8
const template = await getTemplate("../cadence/scripts/get-name.cdc")
9
console.log({template})
10
}
11
12
main()

getContractCode(name, addressMap)

Returns Cadence template from file with name in _basepath_/contracts folder

Arguments

NameTypeOptionalDescription
namestringname of the contract template
addressMapAddressMapobject to use for address mapping of existing deployed contracts

Returns

TypeDescription
stringCadence template code for specified contract

Usage

1
import path from "path"
2
import {init, emulator, getContractCode} from "@onflow/flow-js-testing"
3
4
const main = async () => {
5
const basePath = path.resolve(__dirname, "../cadence")
6
7
await init(basePath)
8
await emulator.start()
9
10
// Let's assume we need to import MessageContract
11
await deployContractByName({name: "MessageContract"})
12
const [MessageContract] = await getContractAddress("MessageContract")
13
const addressMap = {MessageContract}
14
15
const contractTemplate = await getContractCode("HelloWorld", {
16
MessageContract,
17
})
18
console.log({contractTemplate})
19
20
await emulator.stop()
21
}
22
23
main()

getTransactionCode(name, addressMap)

Returns Cadence template from file with name in _basepath_/transactions folder

Arguments

NameTypeOptionalDescription
namestringname of the transaction template
addressMapAddressMapobject to use for address mapping of existing deployed contracts

Returns

TypeDescription
stringCadence template code for specified transaction

Usage

1
import path from "path"
2
import {init, emulator, getTransactionCode} from "@onflow/flow-js-testing"
3
4
const main = async () => {
5
const basePath = path.resolve(__dirname, "../cadence")
6
7
await init(basePath)
8
await emulator.start()
9
10
// Let's assume we need to import MessageContract
11
await deployContractByName({name: "MessageContract"})
12
const [MessageContract] = await getContractAddress("MessageContract")
13
const addressMap = {MessageContract}
14
15
const txTemplate = await getTransactionCode({
16
name: "set-message",
17
addressMap,
18
})
19
console.log({txTemplate})
20
21
await emulator.stop()
22
}
23
24
main()

getScriptCode(name, addressMap)

Returns Cadence template from file with name in _basepath_/scripts folder

Arguments

NameTypeOptionalDescription
namestringname of the script template
addressMapAddressMapobject to use for address mapping of existing deployed contracts

Returns

TypeDescription
stringCadence template code for specified script

Usage

1
import path from "path"
2
import {init, emulator, getScriptCode} from "@onflow/flow-js-testing"
3
4
const main = async () => {
5
const basePath = path.resolve(__dirname, "../cadence")
6
7
await init(basePath)
8
await emulator.start()
9
10
// Let's assume we need to import MessageContract
11
await deployContractByName({name: "MessageContract"})
12
const [MessageContract] = await getContractAddress("MessageContract")
13
const addressMap = {MessageContract}
14
15
const scriptTemplate = await getScriptCode({
16
name: "get-message",
17
addressMap,
18
})
19
20
console.log({scriptTemplate})
21
await emulator.stop()
22
}
23
24
main()

Types

AddressMap

Object to use for address mapping of existing deployed contracts. Key shall be string and value shall be Address

Example

1
const addressMap = {
2
Messanger: "0x01cf0e2f2f715450",
3
Logger: "0x179b6b1cb6755e31",
4
}

Interaction

Interaction is a Promise or function returning a promise.

Example

1
const ix = async () => {
2
return new Promise((resolve, reject) => {
3
setTimeout(() => {
4
resolve(1337)
5
})
6
}, 500)
7
}

CadenceTransformer

Function, which will get valid Cadence code, modify it and return valid Cadence code

Example

This transformer will look for occupancies of specific import statement and replace it with proper address, where it's deployed on Emulator

1
const replaceAddress = async code => {
2
const modified = code.replace(
3
/import\s+FungibleToken\s+from\s+0xFUNGIBLETOKEN/,
4
"import FungibleToken from 0xee82856bf20e2aa6"
5
)
6
7
return modified
8
}

KeyObject

Key objects are used to specify signer keys when creating accounts.

KeyRequiredValue TypeDescription
hashAlgorithmNoHashAlgorithmHashing algorithm to use for generating signatures to be signed by this key (default: HashAlgorithm.SHA3_256)
privateKeyYesstringPrivate key to use to generate the signature
signatureAlgorithmNoSignatureAlgorithmSigning algorithm used to sign transactions with this key (default: SignatureAlgorithm.ECDSA_P256)
weightNonumberWeight of the key - see Flow Core Concepts for more information

PublicKey

Public keys are stored as Buffer objects which have been RLP encoded according to the Flow spec.

In order to generate this object using the Flow JS Testing library, use the pubFlowKey method exported by the library.

1
import {pubFlowKey} from "@onflow/flow-js-testing"
2
3
const pubKey = await pubFlowKey({
4
privateKey: ...,
5
hashAlgorithm: ...,
6
signatureAlgorithm: ...,
7
weight: ...
8
})

SignatureObject

Signature objects are used to represent a signature for a particular message as well as the account and keyId which signed for this message.

KeyValue TypeDescription
addrAddressthe address of the account which this signature has been generated for
keyIdnumberAddress or SignerInfo object representing user to generate this signature for
signaturestringa hexidecimal-encoded string representation of the generated signature

SignerInfoObject

Signer Info objects are used to specify information about which signer and which key from this signer shall be used to sign a transaction.

KeyRequiredValue TypeDescription
addrYesAddressThe address of the signer's account
hashAlgorithmNoHashAlgorithmHashing algorithm to use for generating the signature (default: HashAlgorithm.SHA3_256)
keyIdNonumberThe index of the desired key to use from the signer's account (default: 0)
privateKeyNostringPrivate key to use to generate the signature (default: service account private key - this is the default PK for all accounts generated by Flow JS Testing Library, see: accounts)
signatureAlgorithmNoSignatureAlgorithmSigning algorithm used to generate the signature (default: SignatureAlgorithm.ECDSA_P256)

HashAlgorithm

IdentifierValue
SHA2_2561
SHA3_2563

Hash algorithms may be provided as either an enum (accessible via the HashAlgorithm object exported by Flow JS Testing, i.e. HashAlgorithm.SHA3_256) or as a string representation of their enum identifier (i.e. "SHA3_256")

SignatureAlgorithm

IdentifierValue
ECDSA_P2562
ECDSA_secp256k13

Signing algorithms may be provided as either an enum (accessible via the SignatureAlgorithm object exported by Flow JS Testing, i.e. SignatureAlgorithm.ECDSA_P256) or as a string representation of their enum identifier (i.e. "ECDSA_P256")

Utilities

isAddress(address)

Returns true if the given string is a validly formatted account address (both "0x" prefixed and non-prefixed are valid)

Arguments

NameTypeOptionalDescription
addressstringstring to test against the regex

Returns

TypeDescription
booleanReturns true if given string is a validly formatted account address.

Usage

1
import {isAddress} from "@onflow/flow-js-testing"
2
3
const badAddr = "0xqrtyff"
4
console.log(isAddress(badAddr)) // false
5
6
const goodAddrWithPrefix = "0xf8d6e0586b0a20c1"
7
console.log(isAddress(goodAddrWithPrefix)) // true
8
9
const goodAddrSansPrefix = "f8d6e0586b0a20c1"
10
console.log(isAddress(goodAddrSansPrefix)) // true