chai#expect TypeScript Examples
The following examples show how to use
chai#expect.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: util.test.ts From bodhi.js with Apache License 2.0 | 7 votes |
describe('utils', () => {
it('works with positive numbers', () => {
expect(toBN('1').toString()).to.equal('1');
expect(toBN('0xff').toString()).to.equal('255');
expect(toBN(123).toString()).to.equal('123');
expect(toBN(BigNumber.from(123)).toString()).to.equal('123');
});
it('works with negative numbers', () => {
expect(toBN('-1').toString()).to.equal('-1');
expect(toBN(-123).toString()).to.equal('-123');
expect(toBN(BigNumber.from(-123)).toString()).to.equal('-123');
});
});
Example #2
Source File: util.test.ts From persistent-merkle-tree with Apache License 2.0 | 7 votes |
describe("computeProofGindices", () => {
it("simple implementation should match bitstring implementation", () => {
const gindices = [BigInt(8), BigInt(9), BigInt(14)];
for (const gindex of gindices) {
const simple = computeProofGindices(gindex);
const bitstring = computeProofBitstrings(gindex.toString(2));
expect(new Set([...bitstring.branch].map((str) => BigInt("0b" + str)))).to.deep.equal(simple.branch);
expect(new Set([...bitstring.path].map((str) => BigInt("0b" + str)))).to.deep.equal(simple.path);
}
});
it("should properly compute known testcases", () => {
const testCases = [
{
input: BigInt(8),
output: {branch: new Set([BigInt(9), BigInt(5), BigInt(3)]), path: new Set([BigInt(8), BigInt(4), BigInt(2)])},
},
{
input: BigInt(9),
output: {branch: new Set([BigInt(8), BigInt(5), BigInt(3)]), path: new Set([BigInt(9), BigInt(4), BigInt(2)])},
},
{
input: BigInt(14),
output: {
branch: new Set([BigInt(15), BigInt(6), BigInt(2)]),
path: new Set([BigInt(14), BigInt(7), BigInt(3)]),
},
},
];
for (const {input, output} of testCases) {
const actual = computeProofGindices(input);
expect(actual.branch).to.deep.equal(output.branch);
expect(actual.path).to.deep.equal(output.path);
}
});
});
Example #3
Source File: utils.spec.ts From Correios-Brasil with Apache License 2.0 | 7 votes |
describe('Sanitize Cep', () => {
it('Cep com tamanho inválido', () => {
const invalidCepLength = '123213';
expect(() => sanitization(invalidCepLength)).to.throw();
});
it('Cep com máscara', () => {
const maskedCep = '21770-200';
expect(sanitization(maskedCep)).to.be.equals('21770200');
});
it('Cep sem máscara', () => {
const notMaskedCep = '21770200';
expect(sanitization(notMaskedCep)).to.be.equals('21770200');
});
});
Example #4
Source File: auth.spec.ts From 0Auth with MIT License | 6 votes |
describe('test server utils', () => {
it('test merkle root', () => {
const properties = Array.from(Array(100).keys())
.map((index) => ({
type: PropertyType.Raw,
key: `key${index}`,
value: `value${index}`,
}))
.map((property) => hashProperty(property));
expect(getMerkleRoot(properties)).to.be.equal(
'5f51373a384a121a2d47a4c94c5e3e07ebb994a2f1db99190c2329d5b8e0a1b1',
);
});
it('test public key from key string in ECDSA', () => {
const secretKeyString =
'2ef40452ec154cd38efdc8ffa52e7f513f7d2b2a77e028342bde96c369e4f77a';
const publicKey = publicKeyFromKeyString(secretKeyString, KeyType.ECDSA);
expect(publicKey).to.be.equal(
'048da7b63430eb4db203177baf2e8699a25116561624e67a31c2bf288d54216ce3f6f9c7b81fdbb5732342475a6ee5ccab883277ddbb38fdb79ab5424d401b844a',
);
});
it('test public key from key string in EDDSA', () => {
const secretKeyString =
'2ef40452ec154cd38efdc8ffa52e7f513f7d2b2a77e028342bde96c369e4f77a';
const publicKey = publicKeyFromKeyString(secretKeyString, KeyType.EDDSA);
expect(publicKey).to.be.equal(
'cb7da1efe0ca47d03ff12d1b8f01160debf62c0a2cb2517251f3019d61e0c5f3',
);
});
});
Example #5
Source File: bigint.test.ts From circom-ecdsa with GNU General Public License v3.0 | 6 votes |
describe("BigMult n = 2, k = 1 exhaustive", function() {
this.timeout(1000 * 1000);
// runs circom compilation
let circuit: any;
before(async function () {
circuit = await wasm_tester(path.join(__dirname, "circuits", "test_bigmult_21.circom"));
});
// a, b, div, mod
var test_cases: Array<[bigint, bigint, bigint]> = [];
for (var a = 0n; a < 4; a++) {
for (var b = 0n; b < 4; b++) {
var product = a * b;
test_cases.push([a, b, product]);
}
}
var test_bigmult_21 = function (x: [bigint, bigint, bigint]) {
const [a, b, product] = x;
var a_array: bigint[] = bigint_to_array(2, 1, a);
var b_array: bigint[] = bigint_to_array(2, 1, b);
var product_array: bigint[] = bigint_to_array(2, 2, product);
it('Testing a: ' + a + ' b: ' + b, async function() {
let witness = await circuit.calculateWitness({"a": a_array, "b": b_array});
expect(witness[1]).to.equal(product_array[0]);
expect(witness[2]).to.equal(product_array[1]);
await circuit.checkConstraints(witness);
});
}
test_cases.forEach(test_bigmult_21);
});
Example #6
Source File: index.test.ts From bodhi.js with Apache License 2.0 | 6 votes |
describe('bodhi', () => {
it('should export the Provider', () => {
expect(Provider).to.not.be.undefined;
});
it('default evm address', () => {
const accountid = decodeAddress('5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY');
const encode = u8aConcat('evm:', accountid);
expect(u8aToHex(blake2AsU8a(encode, 256).slice(0, 20))).to.equal('0xf4ca11ca834c9e2fb49f059ab71fb9c72dad05f9');
});
});
Example #7
Source File: Contracts.test.ts From clarity with Apache License 2.0 | 6 votes |
describe('byteHash', () => {
it('should compute the same hash as Scala', () => {
const inputBase64 =
'CiD3h4YVBZm1ChNTR29eLxLNE8IU5RIJZ0HEjn7GNjmvVhABGOO9g5q8LSpA4X7mRaRWddGbdOmIM9Fm9p0QxFKvVBscD5dmu1YdPK29ufR/ZmI0oseKM6l5RVKIUO3hh5en5prtkrrCzl3sdw==';
const input = decodeBase64(inputBase64);
const hash = byteHash(input);
const hashHex = Buffer.from(hash).toString('hex');
const expectedHex =
'e0c7d8fbcbfd7eb5231b779cb4d7dcbcc3d60846e5a198a2c66bb1d3aafbd9a7';
expect(hashHex).to.equal(expectedHex);
expect(hash.length).to.equal(32);
});
});
Example #8
Source File: bytes.test.ts From bls with Apache License 2.0 | 6 votes |
describe("helpers / bytes", () => {
describe("isZeroUint8Array", () => {
const testCases: {isZero: boolean; hex: string}[] = [
{hex: "0x00", isZero: true},
{hex: "0x" + "00".repeat(32), isZero: true},
{hex: "0x" + "00".repeat(96), isZero: true},
{hex: "0x" + "00".repeat(31) + "01", isZero: false},
{
hex: "0xb6f21199594b56d77670564bf422cb331d5281ca2c1f9a45588a56881d8287ef8619efa6456d6cd2ef61306aa5b21311",
isZero: false,
},
];
for (const {hex, isZero} of testCases) {
it(`${hex} isZero = ${isZero}`, () => {
const bytes = hexToBytesNode(hex);
expect(isZeroUint8Array(bytes)).to.equal(isZero);
});
}
});
describe("concatUint8Arrays", () => {
it("Should merge multiple Uint8Array", () => {
const bytesArr = [
new Uint8Array([1, 2, 3]),
new Uint8Array([4, 5]),
new Uint8Array([6]),
new Uint8Array([7, 8]),
new Uint8Array([9, 10, 11]),
];
const expectedBytes = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
const bytes = concatUint8Arrays(bytesArr);
expect(bytes.toString()).to.equal(expectedBytes.toString());
});
});
});
Example #9
Source File: account.test.ts From metamask-snap-polkadot with Apache License 2.0 | 6 votes |
describe('Test account function: getKeyPair', function() {
const walletStub = new WalletMock();
afterEach(function() {
walletStub.reset();
});
it('should return keypair', async function() {
walletStub.getPluginState.returns({polkadot: {configuration: westendConfiguration}});
walletStub.getAppKey.returns(testAppKey);
walletStub.updatePluginState.returnsArg(0);
const result = await getKeyPair(walletStub);
expect(walletStub.getAppKey).to.have.been.calledOnce;
expect(result.address).to.be.eq(testAddress);
expect(result.publicKey).to.be.deep.eq(hexToU8a(testPublicKey));
});
});
Example #10
Source File: hash.test.ts From persistent-merkle-tree with Apache License 2.0 | 6 votes |
describe("hash", function () {
it("hash and hashTwoObjects should be the same", () => {
const root1 = Buffer.alloc(32, 1);
const root2 = Buffer.alloc(32, 2);
const root = hash(root1, root2);
const obj1 = uint8ArrayToHashObject(root1);
const obj2 = uint8ArrayToHashObject(root2);
const obj = hashTwoObjects(obj1, obj2);
const newRoot = hashObjectToUint8Array(obj);
expect(newRoot).to.be.deep.equal(root, "hash and hash2 is not equal");
});
});
Example #11
Source File: call.test.ts From foundry-rpc-js with ISC License | 6 votes |
describe("call", () => {
it("ping", async () => {
const response = await call({
node: "http://localhost:8080",
method: "ping"
});
const result = JSON.parse(response);
expect(result.jsonrpc).equal("2.0");
expect(result.result).equal("pong");
expect(result.id).be.null;
});
it("ping with number id", async () => {
const id = Math.floor(Math.random() * 1000);
const response = await call({
node: "http://localhost:8080",
method: "ping",
id
});
const result = JSON.parse(response);
expect(result.jsonrpc).equal("2.0");
expect(result.result).equal("pong");
expect(result.id).equal(id);
});
it("ping with string id", async () => {
const id = "string id";
const response = await call({
node: "http://localhost:8080",
method: "ping",
id
});
const result = JSON.parse(response);
expect(result.jsonrpc).equal("2.0");
expect(result.result).equal("pong");
expect(result.id).equal(id);
});
});
Example #12
Source File: BlockReorderingServiceTest.ts From DamnVulnerableCryptoApp with MIT License | 6 votes |
describe("BlockReorderingService", () => {
before(TestContext.create);
after(TestContext.reset);
it("Should encrypt token", () => {
expect(BlockReorderingService.encryptToken("dvca")).to.be.equal("4d04658c39fb48269dc741aa6b2c78c0");
});
it("Should decerypt token", () => {
expect(BlockReorderingService.decryptToken("4d04658c39fb48269dc741aa6b2c78c0")).to.be.equal("dvca");
});
it("Should create token adn check that is admin", () => {
const t = BlockReorderingService.createToken("dvca", true);
expect(t).to.match(/[a-f0-9]{128}/);
expect(BlockReorderingService.isAdmin(t)).to.be.true;
});
});
Example #13
Source File: Processor.spec.ts From edge-currency-plugins with MIT License | 6 votes |
makeFixtures = async (): Promise<Fixtures> => {
const storage = {}
const disklet = makeMemoryDisklet(storage)
const processor = await makeProcessor({ disklet })
return {
assertNumAddressesWithPaths: expectedNum => {
const num = processor.numAddressesByFormatPath({
format: 'bip44',
changeIndex: 0
})
expect(num).eql(expectedNum)
},
assertLastUsedByFormatPath: async toBe => {
const result = await processor.lastUsedIndexByFormatPath({
format: 'bip44',
changeIndex: 0
})
expect(result).eql(toBe)
},
assertNumTransactions: (
expectedNum: number,
processor: Processor
): void => {
const num = processor.numTransactions()
expect(num).eql(expectedNum)
},
assertProcessorObjectNotUndefined: <T>(object: T | undefined): T => {
if (object == null)
throw new Error(`unable to retrieve from the processor`)
return object
},
processor
}
}
Example #14
Source File: mailbox_interactions.spec.ts From space-sdk with MIT License | 6 votes |
describe('Mailbox interactions', () => {
it('should be able to setup mailbox', async () => {
const { user } = await authenticateAnonymousUser();
const mb = await Mailbox.createMailbox(user, TestStorageConfig, parseMsg);
}).timeout(TestsDefaultTimeout);
it('should be able to send a mail', async () => {
const { user: user1 } = await authenticateAnonymousUser();
const mb1 = await Mailbox.createMailbox(user1, TestStorageConfig, parseMsg);
const { user: user2, identity: receipient } = await authenticateAnonymousUser();
const mb2 = await Mailbox.createMailbox(user2, TestStorageConfig, parseMsg);
const sentmsg = await mb1.sendMessage(Buffer.from(user2.identity.public.pubKey).toString('hex'), new Uint8Array(8));
expect(sentmsg).not.to.be.null;
expect(sentmsg.id).not.to.be.null;
expect(sentmsg.createdAt).not.to.be.null;
expect(sentmsg.body).not.to.be.null;
expect(sentmsg.to).to.eq(tryParsePublicKey(Buffer.from(user2.identity.public.pubKey).toString('hex')).toString());
expect(sentmsg.from).to.eq(tryParsePublicKey(Buffer.from(user1.identity.public.pubKey).toString('hex')).toString());
const msgs = await mb2.listInboxMessages();
}).timeout(TestsDefaultTimeout);
});
Example #15
Source File: client.spec.ts From 0Auth with MIT License | 5 votes |
describe('test utils', () => {
if (global.localStorage === undefined) {
Object.defineProperty(global, 'localStorage', {
value: mockStorage(),
});
}
beforeEach(() => {
localStorage.clear();
});
it('test LocalStorage Mock', () => {
expect(
getData('test', DataType.Key, StorageType.LocalStorage).orUndefined(),
).to.be.equal(undefined);
expect(
getData('test', DataType.Message, StorageType.LocalStorage).orUndefined(),
).to.be.equal(undefined);
storeData('test', 'stored key', DataType.Key, StorageType.LocalStorage);
storeData(
'test',
'stored message',
DataType.Message,
StorageType.LocalStorage,
);
expect(
getData('test', DataType.Key, StorageType.LocalStorage).get(),
).to.be.equal('stored key');
expect(
getData('test', DataType.Message, StorageType.LocalStorage).get(),
).to.be.equal('stored message');
});
it('test Encrypt & Decrypt message', () => {
const encryptedMessage = encryptMessage('Message', '1q2w3e4r');
const decryptedMessage = decryptMessage(encryptedMessage, '1q2w3e4r');
expect(decryptedMessage).to.be.equal('Message');
expect(
decryptMessage(
'U2FsdGVkX1/tAtcP+fxui5NTWXrmvtO2dV5Z4obDLP4=',
'1q2w3e4r',
),
).to.be.equal('Message');
});
it('test Encrypt & Decrypt Long message', () => {
const message =
"{'properties':[{'key':'name','type':0,'value':'Kim'},{'key':'age','type':0,'value':'17'},{'key':'address','type':0,'value':'Seoul'}],'sign':{'authType':0,'keyType':1,'value':'304402207282d176a100f0d5feb3faa160bd39843253ec98487cc3342905260ab592b85e02201fdf55464c12bbe4b93868a6e84da59e816e918d52cc599678605f61846426c6'}}\n";
const encryptedMessage = encryptMessage(message, '1q2w3e4r');
const decryptedMessage = decryptMessage(encryptedMessage, '1q2w3e4r');
expect(decryptedMessage).to.be.equal(message);
});
it('test Decrypted Message', () => {
expect(
getDecryptedMessage(
'test',
'encryption key',
StorageType.LocalStorage,
).orNull(),
).to.be.null;
storeData(
'test',
encryptMessage('stored message', 'encryption key'),
DataType.Message,
StorageType.LocalStorage,
);
expect(
getDecryptedMessage(
'test',
'encryption key',
StorageType.LocalStorage,
).get(),
).to.be.equal('stored message');
});
});
Example #16
Source File: bigint.test.ts From circom-ecdsa with GNU General Public License v3.0 | 5 votes |
describe("BigMod n = 2, k = 2 exhaustive", function() {
this.timeout(1000 * 1000);
// runs circom compilation
let circuit: any;
before(async function () {
circuit = await wasm_tester(path.join(__dirname, "circuits", "test_bigmod_22.circom"));
});
// a, b, div, mod
var test_cases: Array<[bigint, bigint, bigint, bigint]> = [];
for (var a = 0n; a < 4 * 4 * 4 * 4; a++) {
for (var b = 4n; b < 4 * 4; b++) {
var div = a / b;
var mod = a % b;
test_cases.push([a, b, div, mod]);
}
}
var test_bigmod_22 = function (x: [bigint, bigint, bigint, bigint]) {
const [a, b, div, mod] = x;
var a_array: bigint[] = bigint_to_array(2, 4, a);
var b_array: bigint[] = bigint_to_array(2, 2, b);
var div_array: bigint[] = bigint_to_array(2, 3, div);
var mod_array: bigint[] = bigint_to_array(2, 2, mod);
it('Testing a: ' + a + ' b: ' + b, async function() {
let witness = await circuit.calculateWitness({"a": a_array, "b": b_array});
expect(witness[1]).to.equal(div_array[0]);
expect(witness[2]).to.equal(div_array[1]);
expect(witness[3]).to.equal(div_array[2]);
expect(witness[4]).to.equal(mod_array[0]);
expect(witness[5]).to.equal(mod_array[1]);
await circuit.checkConstraints(witness);
});
}
test_cases.forEach(test_bigmod_22);
});
Example #17
Source File: cache.test.ts From bodhi.js with Apache License 2.0 | 5 votes |
describe('BlockCache', () => {
const EXTRA_BLOCK_COUNT = 15;
const TOTAL_BLOCKS = 80;
const chain = mockChain(TOTAL_BLOCKS);
let cache: BlockCache;
beforeEach(() => {
cache = new BlockCache(EXTRA_BLOCK_COUNT);
});
describe('initialization', () => {
it('initialize two empty map', () => {
expect(cache.blockToHashes).to.deep.equal({});
expect(cache.hashToBlocks).to.deep.equal({});
});
});
describe('add block', () => {
it('correctly find cached transactions, and prune old blocks', () => {
chain.forEach((transactions, latestBlockNumber) => {
cache.addTxsAtBlock(latestBlockNumber, transactions);
const firstBlockInCache = Math.max(0, latestBlockNumber - EXTRA_BLOCK_COUNT + 1);
/* ---------- test inspect ---------- */
const { cachedBlocks } = cache._inspect();
expect(parseInt(cachedBlocks[0])).to.equal(firstBlockInCache);
expect(parseInt(cachedBlocks[cachedBlocks.length - 1])).to.equal(latestBlockNumber);
/* ---------- test getBlockNumber ---------- */
for (let blockNumber = 0; blockNumber < TOTAL_BLOCKS; blockNumber++) {
const isBlockInCache = blockNumber >= firstBlockInCache && blockNumber <= latestBlockNumber;
for (const curTx of chain[blockNumber]) {
expect(cache.getBlockNumber(curTx)).to.equal(isBlockInCache ? blockNumber : undefined);
}
}
});
});
});
});