vitest#describe TypeScript Examples

The following examples show how to use vitest#describe. 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: utils.test.ts    From reskript with MIT License 7 votes vote down vote up
describe('extractName', () => {
    test('simple name', () => {
        expect(extractName({path: 'abc', index: ' ', workingTree: ' '})).toBe('abc');
    });

    test('quoted', () => {
        expect(extractName({path: '"abc"', index: ' ', workingTree: ' '})).toBe('abc');
    });

    test('start quote only', () => {
        expect(extractName({path: '"abc', index: ' ', workingTree: ' '})).toBe('"abc');
    });

    test('end quote only', () => {
        expect(extractName({path: 'abc"', index: ' ', workingTree: ' '})).toBe('abc"');
    });

    test('rename', () => {
        expect(extractName({path: 'xyz -> "abc"', index: 'R', workingTree: ' '})).toBe('abc');
    });

    test('copy', () => {
        expect(extractName({path: 'xyz -> "abc"', index: 'C', workingTree: ' '})).toBe('abc');
    });
});
Example #2
Source File: VPerfectSignature.test.ts    From v-perfect-signature with MIT License 6 votes vote down vote up
describe('#isEmpty', () => {
  it('returns true if pad is empty', () => {
    const wrapper = shallowMount(VPerfectSignature)

    expect(wrapper.vm.isEmpty()).toBe(true)
  })

  it('returns false if pad is not empty', () => {
    const wrapper = shallowMount(VPerfectSignature)

    wrapper.setData({
      allInputPoints: inputPointsMockData,
    })

    expect(wrapper.vm.isEmpty()).toBe(false)
  })
})
Example #3
Source File: parse-public-key.spec.ts    From cloud-cryptographic-wallet with MIT License 6 votes vote down vote up
describe("parsePublicKey", () => {
  it("should be parse (AWS KMS)", () => {
    const bytes = Bytes.fromString(
      "3056301006072a8648ce3d020106052b8104000a034200046ce651c2445abd0915d97b683ff35cc6de4c340b8759918fd34cacf4395c39b0e2ad7517c9ab585ed5213ef0c00a1896f390eb03ff1ef8a13e18f036fa62a9e4"
    );

    const publicKey = parsePublicKey(bytes.buffer);

    const expected = Address.fromBytes(
      Bytes.fromString("0b45ff0aea02cb12b8923743ecebc83fe437c614")
    );

    expect(
      expected.equals(
        PublicKey.fromBytes(Bytes.fromArrayBuffer(publicKey)).toAddress()
      )
    );
  });

  it("should be parse (Cloud KMS)", () => {
    const bytes = Bytes.fromString(
      "3056301006072a8648ce3d020106052b8104000a03420004d4f664a42f91df474e4e97549f773a187ed85f93af9fc4053a29961d9c810ea33c8894a313631c7eee83916ef32ad5dbc321f06b1d600f039eee22488d6b48d1"
    );

    const publicKey = parsePublicKey(bytes.buffer);

    const expected = Address.fromBytes(
      Bytes.fromString("0x9f60980a13f74d79214e258d2f52fd846a3a5511")
    );

    expect(
      expected.equals(
        PublicKey.fromBytes(Bytes.fromArrayBuffer(publicKey)).toAddress()
      )
    );
  });
});
Example #4
Source File: processDatabase.test.ts    From kanel with MIT License 6 votes vote down vote up
describe('processDatabase', () => {
  it('should process the dvd rental example according to the snapshot', async () => {
    await processDatabase({
      connection: {},

      preDeleteModelFolder: false,

      customTypeMap: {
        tsvector: {
          name: 'TsVector',
          module: 'ts-vector',
          absoluteImport: true,
          defaultImport: true,
        },
        bpchar: 'string',
      },

      resolveViews: true,

      schemas: [
        {
          name: 'public',
          modelFolder: '/models',
          ignore: ['film_list', 'staff'],
        },
      ],
    });

    // @ts-ignore
    const results = writeFile.mock.calls;
    expect(results).toMatchSnapshot();
  });
});
Example #5
Source File: index.spec.ts    From volar with MIT License 6 votes vote down vote up
describe(`vue-tsc`, () => {
	it(`vue-tsc no errors`,  () => new Promise((resolve, reject) => {
		const cp = fork(
			binPath,
			['--noEmit'],
			{
				silent: true,
				cwd: path.resolve(__dirname, '../../vue-test-workspace')
			},
		);

		cp.stdout.setEncoding('utf8');
		cp.stdout.on('data', (data) => {
			console.log(data);
		});
		cp.stderr.setEncoding('utf8');
		cp.stderr.on('data', (data) => {
			console.error(data);
		});

		cp.on('exit', (code) => {
			if(code === 0) {
				resolve();
			} else {
				reject(new Error(`Exited with code ${code}`));
			}
		});
 	}), 40_000);
});
Example #6
Source File: assert-known-address.spec.ts    From cloud-cryptographic-wallet with MIT License 6 votes vote down vote up
describe("assertKnownAddress", () => {
  const from = "0x0a7943653138accf65145bbfdf3dfbc124267a61";
  const addresses = [
    "0xbba0631f67f6eff9d5a86052244ee477dd85b010",
    "0x137e74c5986e81a26e76a7fe47553fe2f1361b57",
    "0x569a6dc26ba89b30f94708fddc5b760ed5974eaf",
  ];

  describe("when pass to known address", () => {
    it("nothing", async () => {
      assertKnownAddress(from, [from, ...addresses]);
    });
  });
  describe("when pass to unknown address", () => {
    it("throw error", async () => {
      expect(() => assertKnownAddress(from, addresses)).toThrow(
        /from is unknown address/
      );
    });
  });
});
Example #7
Source File: markdown-image-parsing.test.ts    From obsidian-imgur-plugin with MIT License 6 votes vote down vote up
describe("isWrapped type predicate", () => {
  it("treats simple image as not-wrapped", () => {
    const matchedPieces = findImgurMarkdownImage(
      "![](https://i.imgur.com/m3RpPCV.png)",
      0
    ).mdImagePieces;
    expect(isWrapped(matchedPieces)).toBeFalsy();
  });

  it("correctly detects wrapped image", () => {
    const matchedPieces = findImgurMarkdownImage(
      "[![](https://i.imgur.com/m3RpPCVs.png)](https://i.imgur.com/m3RpPCV.png)",
      0
    ).mdImagePieces;
    expect(isWrapped(matchedPieces)).toBeTruthy();
  });
});
Example #8
Source File: ethers-send-eth.spec.ts    From cloud-cryptographic-wallet with MIT License 6 votes vote down vote up
describe("ethers", () => {
  beforeEach(async () => {
    const provider = new ethers.providers.JsonRpcProvider(rpcUrl);
    const wallet = provider.getSigner();

    const signer = new KmsEthersSigner({ keyId, kmsClientConfig: { region } });

    await wallet.sendTransaction({
      to: await signer.getAddress(),
      value: ethers.utils.parseEther("1"),
    });
  });

  it("send eth", async () => {
    const provider = new ethers.providers.JsonRpcProvider(rpcUrl);
    const signer = new KmsEthersSigner({
      keyId,
      kmsClientConfig: { region },
    }).connect(provider);

    const target = crypto.randomBytes(20).toString("hex");

    const value = ethers.utils.parseEther("0.5");

    const transaction = await signer.sendTransaction({
      to: target,
      value,
    });

    await transaction.wait();

    const actual = await provider.getBalance(target);
    expect(actual.eq(value)).toBeTruthy();
  });
});
Example #9
Source File: utils.test.ts    From reskript with MIT License 6 votes vote down vote up
describe('filterStagedOnly', () => {
    test('exclude modified', () => {
        const names = filterStagedOnly(diff).map(v => v.path);
        expect(names).toEqual(['2', '4 -> 5', '9', '10']);
    });
});
Example #10
Source File: VPerfectSignature.test.ts    From v-perfect-signature with MIT License 6 votes vote down vote up
describe('#clear', () => {
  it('clears data structures and pad', () => {
    const wrapper = shallowMount(VPerfectSignature)

    wrapper.setData({
      allInputPoints: inputPointsMockData,
    })
    wrapper.vm.clear()

    expect(wrapper.vm.toData()).toEqual([])
  })
})
Example #11
Source File: contract.test.ts    From ethcall with MIT License 6 votes vote down vote up
describe('Contract', () => {
  test('inits a contract', () => {
    const address = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2';
    const contract = new Contract(address, erc20Abi);
    expect(contract.address).toEqual(address);
    expect(contract.abi).toEqual(erc20Abi);
  });

  test('creates a call', () => {
    const address = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2';
    const contract = new Contract(address, erc20Abi);
    const ownerCall = contract.name() as Call;
    expect(ownerCall.contract.address).toEqual(address);
    expect(ownerCall.name).toEqual('name');
  });
});
Example #12
Source File: VPerfectSignature.test.ts    From v-perfect-signature with MIT License 6 votes vote down vote up
describe('#fromDataURL', () => {
  it('should set signature from data uri', async() => {
    const wrapper = shallowMount(VPerfectSignature)
    await expect(wrapper.vm.fromDataURL(mockDataURL)).resolves.toBe(true)
  })

  spyOn(console, 'error').mockImplementation(() => {})

  it('fails if data uri is incorrect', async() => {
    const wrapper = shallowMount(VPerfectSignature)

    await expect(wrapper.vm.fromDataURL('random string')).rejects.toThrow(
      'Incorrect data uri provided',
    )
  })
})
Example #13
Source File: time.test.ts    From osmosfeed with MIT License 6 votes vote down vote up
describe("getOffsetFromTimezoneName", () => {
  it("handles url that doesn't need encoding", () => {
    // Note that the symbol is inverted from international convention
    // Source: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
    expect(getOffsetFromTimezoneName("Asia/Shanghai")).toBe(-480); // GMT+8
    expect(getOffsetFromTimezoneName("Asia/Tokyo")).toBe(-540); // GMT+9
    expect(getOffsetFromTimezoneName("UTC")).toBe(0);
    expect(getOffsetFromTimezoneName("EST")).toBe(300); // GMT-5
    expect(getOffsetFromTimezoneName("Pacific/Honolulu")).toBe(600); //GMT-10
  });
});
Example #14
Source File: index.test.ts    From reskript with MIT License 6 votes vote down vote up
describe('base config', () => {
    test('getParseOnlyBabelConfig', () => {
        const config = getParseOnlyBabelConfig(options);
        expect(config).toBeTruthy();
        expect(config.presets).toBeTruthy();
        expect(config.plugins).toBeTruthy();
    });

    test('getTransformBabelConfig', () => {
        const config = getTransformBabelConfig(options);
        expect(config).toBeTruthy();
        expect(config.presets).toBeTruthy();
        expect(config.plugins).toBeTruthy();
    });

    test('getBabelConfig', () => {
        const config = getBabelConfig(options);
        expect(config).toBeTruthy();
        expect(config.presets).toBeTruthy();
        expect(config.plugins).toBeTruthy();
    });
});
Example #15
Source File: normalize-url.test.ts    From osmosfeed with MIT License 6 votes vote down vote up
describe("normalizeUrl", () => {
  it("handles url that doesn't need encoding", async () => {
    await expect(normalizeUrl("https://www.mockdomain.com")).toEqual("https://www.mockdomain.com");
  });

  it("handles url that needs encoding", async () => {
    await expect(normalizeUrl("https://www.mockdomain.com/hello world")).toEqual(
      "https://www.mockdomain.com/hello%20world"
    );
  });

  it("handles url that is encoded", async () => {
    await expect(normalizeUrl("https://www.mockdomain.com/hello%20world")).toEqual(
      "https://www.mockdomain.com/hello%20world"
    );
  });

  it("handles url unicode characters", async () => {
    await expect(normalizeUrl("https://www.你好.com?query=世界")).toEqual(
      "https://www.%E4%BD%A0%E5%A5%BD.com?query=%E4%B8%96%E7%95%8C"
    );
  });
});
Example #16
Source File: send-eth.spec.ts    From cloud-cryptographic-wallet with MIT License 5 votes vote down vote up
describe("web3.js send-eth", () => {
  it.skip("CloudKmsSigner", async () => {
    const name =
      "projects/aws-kms-provider/locations/asia-northeast1/keyRings/for-e2e-test/cryptoKeys/for-e2e-test/cryptoKeyVersions/1";

    const cloudKmsSigner = new CloudKmsSigner(name);
    const provider = createProvider({ signers: [cloudKmsSigner], rpcUrl });
    const web3 = new Web3(provider as never);

    const accounts = await web3.eth.getAccounts();

    const target = crypto.randomBytes(20).toString("hex");

    await prepare(rpcUrl, accounts[0]);

    const value = web3.utils.toWei("0.1", "ether");
    const {
      beforeToBalance,
      afterToBalance,
      beforeFromBalance,
      afterFromBalance,
      cumulativeGasUsed,
      effectiveGasPrice,
    } = await sendEth(accounts[0], target, value, web3);

    const gas = cumulativeGasUsed.mul(effectiveGasPrice);

    expect(
      beforeFromBalance.sub(afterFromBalance).sub(gas).eq(new BN(value))
    ).toBeTruthy();

    expect(afterToBalance.sub(beforeToBalance).eq(new BN(value))).toBeTruthy();
  });

  it("AwsKmsSigner", async () => {
    const keyId = "e9005048-475f-4767-9f2d-0d1fb0c89caf";
    const region = "us-east-1";
    const awsKmsSigner = new AwsKmsSigner(keyId, { region });

    const provider = createProvider({ signers: [awsKmsSigner], rpcUrl });
    const web3 = new Web3(provider as never);

    const accounts = await web3.eth.getAccounts();

    const target = crypto.randomBytes(20).toString("hex");

    await prepare(rpcUrl, accounts[0]);

    const value = web3.utils.toWei("0.1", "ether");
    const {
      beforeToBalance,
      afterToBalance,
      beforeFromBalance,
      afterFromBalance,
      cumulativeGasUsed,
      effectiveGasPrice,
    } = await sendEth(accounts[0], target, value, web3);

    const gas = cumulativeGasUsed.mul(effectiveGasPrice);

    expect(
      beforeFromBalance.sub(afterFromBalance).sub(gas).eq(new BN(value))
    ).toBeTruthy();

    expect(afterToBalance.sub(beforeToBalance).eq(new BN(value))).toBeTruthy();
  });
});
Example #17
Source File: importGenerator.test.ts    From kanel with MIT License 5 votes vote down vote up
describe('ImportGenerator', () => {
  it('should generate an import statement', () => {
    const ig = new ImportGenerator('/src');

    ig.addImport('func', true, '/src/lib/func', false);

    const generatedLines = ig.generateLines();
    expect(generatedLines).toEqual(["import func from './lib/func';"]);
  });

  it('should support various cases', () => {
    const ig = new ImportGenerator('/package/src');

    ig.addImport('defaultFunc', true, '/package/src/lib/defaultFunc', false);

    ig.addImport('namedFunc1', false, '/package/src/lib/namedFunc', false);
    ig.addImport('namedFunc2', false, '/package/src/lib/namedFunc', false);

    ig.addImport('pck', true, '/package/package.json', false);

    ig.addImport('sister', true, '/package/sister-src/sister', false);

    ig.addImport('defComb', true, '/package/src/comb', false);
    ig.addImport('defNamed1', false, '/package/src/comb', false);
    ig.addImport('defNamed2', false, '/package/src/comb', false);
    ig.addImport('defNamed3', false, '/package/src/comb', false);

    const generatedLines = ig.generateLines();
    expect(generatedLines).toEqual([
      "import defaultFunc from './lib/defaultFunc';",
      "import { namedFunc1, namedFunc2 } from './lib/namedFunc';",
      "import pck from '../package.json';",
      "import sister from '../sister-src/sister';",
      "import defComb, { defNamed1, defNamed2, defNamed3 } from './comb';",
    ]);
  });

  it('should ignore duplicates', () => {
    const ig = new ImportGenerator('./');

    ig.addImport('def', true, './pkg', false);
    ig.addImport('def', true, './pkg', false);

    ig.addImport('named1', false, './pkg', false);
    ig.addImport('named2', false, './pkg', false);
    ig.addImport('named1', false, './pkg', false);

    const generatedLines = ig.generateLines();
    expect(generatedLines).toEqual([
      "import def, { named1, named2 } from './pkg';",
    ]);
  });

  it('should complain about multiple (different) default imports', () => {
    const ig = new ImportGenerator('./');

    ig.addImport('def', true, './pkg', false);

    expect(() => ig.addImport('def2', true, './pkg', false)).toThrow(
      "Multiple default imports attempted: def and def2 from './pkg'"
    );
  });

  it('should support aboslute imports', () => {
    const ig = new ImportGenerator('./');

    ig.addImport('path', true, 'path', true);
    ig.addImport('existsSync', false, 'fs', true);
    ig.addImport('mkDirSync', false, 'fs', true);

    const generatedLines = ig.generateLines();
    expect(generatedLines).toEqual([
      "import path from 'path';",
      "import { existsSync, mkDirSync } from 'fs';",
    ]);
  });
});
Example #18
Source File: get-nonce.spec.ts    From cloud-cryptographic-wallet with MIT License 5 votes vote down vote up
describe("getNonce", () => {
  const rpcUrl = "http://locahost:8545";
  const from = "0x9f60980a13f74d79214E258D2F52Fd846A3a5511";

  const server = getServer(rpcUrl, []);

  beforeAll(() => server.listen());
  afterEach(() => server.resetHandlers());
  afterAll(() => server.close());

  describe("when return nonce", () => {
    const nonce = "0x10";
    beforeEach(() => {
      server.use(
        makeHandler(rpcUrl, {
          method: "eth_getTransactionCount",
          result: nonce,
        })
      );
    });

    it("shoud be get nonce", async () => {
      await expect(getNonce(rpcUrl, from)).resolves.toBe(nonce);
    });
  });

  describe("when return null", () => {
    beforeEach(() => {
      server.use(
        makeHandler(rpcUrl, {
          method: "eth_getTransactionCount",
          result: null,
        })
      );
    });

    it("shoud be throw error", async () => {
      await expect(getNonce(rpcUrl, from)).rejects.toThrow(
        /can't get result of eth_getTransactionCount/
      );
    });
  });
});
Example #19
Source File: filter.test.ts    From d3-graph-controller with MIT License 5 votes vote down vote up
describe.concurrent('filter', () => {
  it('can filter nothing', () => {
    const filteredResult = filterGraph({
      filter: ['first', 'second'],
      focusedNode: undefined,
      includeUnlinked: true,
      linkFilter: () => true,
      graph: TestData.graph,
    })
    expect(filteredResult).toEqual(TestData.graph)
  })

  it('can filter by type', () => {
    const filteredResult = filterGraph({
      filter: ['first'],
      focusedNode: undefined,
      includeUnlinked: false,
      linkFilter: () => true,
      graph: TestData.graph,
    })
    expect(filteredResult.nodes).toEqual(
      TestData.graph.nodes.filter((node) => node.type === 'first')
    )
  })

  it('can filter unlinked', () => {
    const filteredResult = filterGraph({
      filter: ['first', 'second'],
      focusedNode: undefined,
      includeUnlinked: false,
      linkFilter: () => true,
      graph: TestData.graph,
    })
    expect(filteredResult.nodes).toEqual(
      TestData.graph.nodes.filter((node) =>
        TestData.graph.links.some(
          (link) => link.source.id === node.id || link.target.id === node.id
        )
      )
    )
    expect(filteredResult.links).toEqual(TestData.graph.links)
  })

  it('can filter links', () => {
    const filteredResult = filterGraph({
      filter: ['first', 'second'],
      focusedNode: undefined,
      includeUnlinked: true,
      linkFilter: (link: GraphLink<TestNodeType>) =>
        link.source.id === link.target.id,
      graph: TestData.graph,
    })
    expect(filteredResult.links.length).toEqual(1)
  })
})
Example #20
Source File: abi.test.ts    From ethcall with MIT License 5 votes vote down vote up
describe('ABI', () => {
  test('encodes input', () => {
    expect(Abi.encode(ownerFunction.name, ownerFunction.inputs, [])).toEqual(
      '0x8da5cb5b',
    );
    expect(
      Abi.encode(balanceOfFunction.name, balanceOfFunction.inputs, [
        '0x1a9c8182c09f50c8318d769245bea52c32be35bc',
      ]),
    ).toEqual(
      '0x70a082310000000000000000000000001a9c8182c09f50c8318d769245bea52c32be35bc',
    );
    expect(
      Abi.encode(swapFunction.name, swapFunction.inputs, [
        {
          inAmount: '250000000',
          inAsset: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
          outAsset: '0x6b175474e89094c44da98b954eedeac495271d0f',
        },
        '1633000000',
      ]),
    ).toEqual(
      '0xa18d33e1000000000000000000000000000000000000000000000000000000000ee6b280000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000006b175474e89094c44da98b954eedeac495271d0f0000000000000000000000000000000000000000000000000000000061559a40',
    );
  });

  test('encodes constructor input', () => {
    expect(Abi.encodeConstructor(ownerFunction.inputs, [])).toEqual('0x');
    expect(
      Abi.encodeConstructor(balanceOfFunction.inputs, [
        '0x1a9c8182c09f50c8318d769245bea52c32be35bc',
      ]),
    ).toEqual(
      '0x0000000000000000000000001a9c8182c09f50c8318d769245bea52c32be35bc',
    );
    expect(
      Abi.encodeConstructor(swapFunction.inputs, [
        {
          inAmount: '250000000',
          inAsset: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
          outAsset: '0x6b175474e89094c44da98b954eedeac495271d0f',
        },
        '1633000000',
      ]),
    ).toEqual(
      '0x000000000000000000000000000000000000000000000000000000000ee6b280000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000006b175474e89094c44da98b954eedeac495271d0f0000000000000000000000000000000000000000000000000000000061559a40',
    );
  });

  test('decodes output', () => {
    expect(
      Abi.decode(
        ownerFunction.name,
        ownerFunction.outputs,
        '0x000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
      ),
    ).toEqual(['0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48']);
    expect(
      Abi.decode(
        balanceOfFunction.name,
        balanceOfFunction.outputs,
        '0x000000000000000000000000000000000000000000000000bb59a27953c60000',
      ).map((a) => a.toString()),
    ).toEqual(['13500000000000000000']);
    expect(Abi.decode(swapFunction.name, swapFunction.outputs, '0x')).toEqual(
      [],
    );
  });
});
Example #21
Source File: parse-signature.spec.ts    From cloud-cryptographic-wallet with MIT License 5 votes vote down vote up
describe("parseSignature", () => {
  describe("when 142-length signature", () => {
    it("should be parse", () => {
      const bytes = Bytes.fromString(
        "304502201fa98c7c5f1b964a6b438d9283adf30519aaea2d1a2b25ac473ac0f85d6e08c0022100e26f7c547cf497959af070ec7c43ebdbb3e4341395912d6ccc950b43e886781b"
      );

      const signature = parseSignature(bytes.buffer);

      const r = Bytes.fromArrayBuffer(signature.r);
      const s = Bytes.fromArrayBuffer(signature.s);

      expect(
        r.equals(
          Bytes.fromString(
            "1fa98c7c5f1b964a6b438d9283adf30519aaea2d1a2b25ac473ac0f85d6e08c0"
          )
        )
      ).toBeTruthy();
      expect(
        s.equals(
          Bytes.fromString(
            "e26f7c547cf497959af070ec7c43ebdbb3e4341395912d6ccc950b43e886781b"
          )
        )
      ).toBeTruthy();

      expect(r.length).toBe(32);
      expect(s.length).toBe(32);
    });
  });
  describe("when 140-length signature", () => {
    it("should be parse", () => {
      const bytes = Bytes.fromString(
        "30440221009c68bf9b88814142fef77d95956b21625789c34fde9b853653b24fc23515577f021f74e3e4d71e7385ae71042b0f99f7fbbf66e7760dd513ed2fcea754e2a9131c"
      );

      const signature = parseSignature(bytes.buffer);

      const r = Bytes.fromArrayBuffer(signature.r);
      const s = Bytes.fromArrayBuffer(signature.s);

      expect(
        r.equals(
          Bytes.fromString(
            "9c68bf9b88814142fef77d95956b21625789c34fde9b853653b24fc23515577f"
          )
        )
      ).toBeTruthy();
      expect(
        s.equals(
          Bytes.fromString(
            "0074e3e4d71e7385ae71042b0f99f7fbbf66e7760dd513ed2fcea754e2a9131c"
          )
        )
      ).toBeTruthy();

      expect(r.length).toBe(32);
      expect(s.length).toBe(32);
    });
  });

  describe("when invalid input", () => {
    it("should be throw Error", () => {
      const bytes = Bytes.fromString("abcd");

      expect(() => parseSignature(bytes.buffer)).toThrow(
        /parseSignature: failed to parse/
      );
    });
  });
});
Example #22
Source File: config.test.ts    From d3-graph-controller with MIT License 5 votes vote down vote up
describe.concurrent('Config', () => {
  describe('can be defined', () => {
    it('using default values', () => {
      const config = defineGraphConfig()
      expect(config).toMatchSnapshot()
    })

    it('with deep merging', () => {
      const defaultConfig = defineGraphConfig()
      const customConfig = defineGraphConfig({
        simulation: {
          forces: {
            collision: {
              radiusMultiplier: 42,
            },
          },
        },
      })
      const customCollisionForce = customConfig.simulation.forces.collision
      expect(customCollisionForce).not.toBe(false)
      // @ts-expect-error It has been asserted that the force is not false
      expect(customCollisionForce.radiusMultiplier).toEqual(42)
      expect(customConfig).not.toEqual(defaultConfig)

      const customMerge = {
        ...defaultConfig,
        simulation: {
          ...defaultConfig.simulation,
          forces: {
            ...defaultConfig.simulation.forces,
            collision: {
              ...defaultConfig.simulation.forces.collision,
              radiusMultiplier: 42,
            },
          },
        },
      }
      expect(customMerge.simulation.forces).toStrictEqual(
        customConfig.simulation.forces
      )
    })
  })
})
Example #23
Source File: defineRename.ts    From volar with MIT License 5 votes vote down vote up
export function defineRename(action: {
	fileName: string,
	position: vscode.Position,
	newName: string,
	length: number,
}, expectedResult: Record<string, string>) {

	const fileName = action.fileName;
	const uri = shared.fsPathToUri(fileName);

	describe(`renaming ${path.basename(fileName)}`, () => {
		for (let i = 0; i < action.length; i++) {
			const location = `${path.relative(volarRoot, fileName)}:${action.position.line + 1}:${action.position.character + i + 1}`;
			it(`rename ${location} => ${action.newName}`, async () => {
				const result = await tester.languageService.doRename(
					uri,
					{ line: action.position.line, character: action.position.character + i },
					action.newName,
				);

				expect(!!result?.changes).toEqual(true);
				if (!result?.changes) return;

				expect(Object.keys(result.changes).length).toEqual(Object.keys(expectedResult).length);

				for (const fileName in expectedResult) {

					const textEdits = result?.changes?.[shared.fsPathToUri(fileName)];
					expect(!!textEdits).toEqual(true);
					if (!textEdits) continue;

					const renameScript = tester.host.getScriptSnapshot(fileName);
					expect(!!renameScript).toEqual(true);
					if (!renameScript) continue;

					const renameScriptText = renameScript.getText(0, renameScript.getLength());
					const renameScriptResult = TextDocument.applyEdits(TextDocument.create('', '', 0, renameScriptText), textEdits);
					expect(normalizedText(renameScriptResult)).toEqual(normalizedText(expectedResult[fileName]));

				}
			});
		}
	});
}
Example #24
Source File: loveMsg.test.ts    From notify-server with MIT License 5 votes vote down vote up
describe('test goodMorning', () => {
  it('work', async () => {})
})
Example #25
Source File: markdown-image-parsing.test.ts    From obsidian-imgur-plugin with MIT License 5 votes vote down vote up
describe("findImgurMarkdownImage", () => {
  const simplestImage = "![](https://i.imgur.com/m3RpPCV.png)";

  it.each([
    { line: simplestImage, cursorAt: 0 },
    { line: simplestImage, cursorAt: 35 },
    { line: "![](https://i.imgur.com/m3RpPCVm.png)", cursorAt: 0 },
  ])("GIVEN line '$line' and cursor pos: $cursorAt", ({ line, cursorAt }) => {
    const match = findImgurMarkdownImage(line, cursorAt);
    expect(match.exists).toBeTruthy();
  });

  it("matches an image when cursor position is set to last character of image", () => {
    const match = findImgurMarkdownImage(simplestImage, 35);
    expect(match.exists).toBeTruthy();
  });

  it("does not match an image when cursor position is after an image", () => {
    const match = findImgurMarkdownImage(simplestImage, 36);
    expect(match.exists).toBeFalsy();
  });

  it("matches 2nd image when cursor is between the 1st and second one", () => {
    const match = findImgurMarkdownImage(
      "![](https://i.imgur.com/m3RpPCV.png)![](https://i.imgur.com/pLIMYhw.png)",
      36
    );
    expect(match.exists).toBeTruthy();
    expect(match.mdImagePieces.imageId).toBe("pLIMYhw");
  });

  it("throws error for images with unexpected length of image id", () => {
    it.each([
      { line: "![](https://i.imgur.com/m3RpPCVsm.png)" },
      { line: "![](https://i.imgur.com/m3RpPC.png)" },
    ])(
      "GIVEN line '$line' an error reporting incorrect image id size will be thrown",
      ({ line }) => {
        const match = findImgurMarkdownImage(line, 0);
        expect(match.mdImagePieces).toThrowError();
      }
    );
  });
});
Example #26
Source File: html.test.ts    From reskript with MIT License 5 votes vote down vote up
describe('injectIntoHtml', () => {
    test('head start has head', () => {
        const output = injectIntoHtml(
            '<html><head></head></html>',
            {headStart: 'foo'}
        );
        expect(output.includes('<head>foo</head>')).toBe(true);
    });

    test('head start no head', () => {
        const output = injectIntoHtml(
            '<html></html>',
            {headStart: 'foo'}
        );
        expect(output.includes('<head>foo</head>')).toBe(true);
    });

    test('head end has head', () => {
        const output = injectIntoHtml(
            '<html><head></head></html>',
            {headEnd: 'foo'}
        );
        expect(output.includes('<head>foo</head>')).toBe(true);
    });

    test('head end no head', () => {
        const output = injectIntoHtml(
            '<html></html>',
            {headStart: 'foo'}
        );
        expect(output.includes('<head>foo</head>')).toBe(true);
    });

    test('body start has head', () => {
        const output = injectIntoHtml(
            '<html><head></head></html>',
            {bodyStart: 'foo'}
        );
        expect(output.includes('<head></head>foo')).toBe(true);
    });

    test('body start no head', () => {
        const output = injectIntoHtml(
            '<html></html>',
            {bodyStart: 'foo'}
        );
        expect(output.includes('</head>foo')).toBe(true);
    });

    test('body end has body', () => {
        const output = injectIntoHtml(
            '<html><body></body></html>',
            {bodyStart: 'foo'}
        );
        expect(output.includes('foo</body>')).toBe(true);
    });

    test('body end no body has html', () => {
        const output = injectIntoHtml(
            '<html></html>',
            {bodyEnd: 'foo'}
        );
        expect(output.includes('foo</html>')).toBe(true);
    });

    test('body end no body no html', () => {
        const output = injectIntoHtml(
            '<html>',
            {bodyEnd: 'foo'}
        );
        expect(output.includes('<html>foo')).toBe(true);
    });
});
Example #27
Source File: controller.test.ts    From d3-graph-controller with MIT License 4 votes vote down vote up
describe('GraphController', () => {
  let container: HTMLDivElement
  let controller: GraphController<TestNodeType>

  beforeEach(() => {
    container = document.createElement('div')
    controller = new GraphController(container, TestData.graph, TestData.config)
  })

  afterEach(() => controller.shutdown())

  it('matches the snapshot', () => {
    expect(container).toMatchSnapshot()
  })

  it('renders nodes', () => {
    expect(container.querySelectorAll('.node').length).toEqual(
      TestData.graph.nodes.length
    )
  })

  it('renders links', () => {
    expect(container.querySelectorAll('.link').length).toEqual(
      TestData.graph.links.length
    )
  })

  describe('can be configured', () => {
    describe('with initial settings', () => {
      it('that set the node type filter', () => {
        controller = new GraphController(
          container,
          TestData.graph,
          defineGraphConfig<TestNodeType>({ initial: { nodeTypeFilter: [] } })
        )

        expect(controller.nodeTypeFilter).toEqual([])
        expect(container.querySelectorAll('.node').length).toEqual(0)
        expect(container.querySelectorAll('.link').length).toEqual(0)
      })

      it('that exclude unlinked nodes', () => {
        controller = new GraphController(
          container,
          TestData.graph,
          defineGraphConfig<TestNodeType>({
            initial: { includeUnlinked: false },
          })
        )

        expect(controller.includeUnlinked).toEqual(false)
        expect(container.querySelectorAll('.node').length).toEqual(3)
      })

      it('that filter links', () => {
        controller = new GraphController(
          container,
          TestData.graph,
          defineGraphConfig<TestNodeType>({
            initial: {
              linkFilter: (link: GraphLink<TestNodeType>) =>
                link.source.id === link.target.id,
            },
          })
        )

        expect(container.querySelectorAll('.link').length).toEqual(1)
      })
    })
  })

  describe('has settings that', () => {
    it('can exclude unlinked nodes', () => {
      expect(container.querySelectorAll('.node').length).toEqual(
        TestData.graph.nodes.length
      )

      controller.includeUnlinked = false

      expect(container.querySelectorAll('.node').length).toEqual(3)
    })

    it('can filter links', () => {
      expect(container.querySelectorAll('.link').length).toEqual(
        TestData.graph.links.length
      )

      controller.linkFilter = (link: GraphLink<TestNodeType>) =>
        link.source.id === link.target.id

      expect(container.querySelectorAll('.link').length).toEqual(1)
    })

    it('can filter by node type', () => {
      const currentlyExcluded: TestNodeType[] = []

      const checkIncludedNodes = () => {
        expect(container.querySelectorAll('.node').length).toEqual(
          TestData.graph.nodes.filter(
            (node) => !currentlyExcluded.includes(node.type)
          ).length
        )
      }

      checkIncludedNodes()

      controller.filterNodesByType(false, 'second')
      currentlyExcluded.push('second')
      checkIncludedNodes()

      controller.filterNodesByType(false, 'first')
      currentlyExcluded.push('first')
      checkIncludedNodes()

      controller.filterNodesByType(true, 'first')
      currentlyExcluded.pop()
      checkIncludedNodes()

      controller.filterNodesByType(true, 'second')
      currentlyExcluded.pop()
      checkIncludedNodes()
    })
  })
})
Example #28
Source File: validate.test.ts    From reskript with MIT License 4 votes vote down vote up
describe('validate', () => {
    test('empty', () => {
        expect(() => validate({})).not.toThrow();
    });

    test('uses pass', () => {
        expect(() => validate({build: {uses: ['antd']}})).not.toThrow();
    });

    test('uses invalid value', () => {
        expect(() => validate({build: {uses: ['unwanted']}})).toThrow();
    });

    test('additional properties', () => {
        const settings = {
            foo: 'bar',
        };

        expect(() => validate(settings)).toThrow();
    });

    test('additional properties in build', () => {
        const settings = {
            build: {
                foo: 'bar',
            },
        };

        expect(() => validate(settings)).toThrow();
    });

    test('additional properties in devServer', () => {
        const settings = {
            devServer: {
                foo: 'bar',
            },
        };

        expect(() => validate(settings)).toThrow();
    });

    test('invalid plugins', () => {
        const settings = {
            plugins: [
                {},
                123,
                421412,
            ],
        };

        expect(() => validate(settings)).toThrow();
    });

    test('feature matrix', () => {
        const settings = {
            featureMatrix: {
                stable: {
                    track: false,
                    date: '2020-06-01',
                },
                dev: {
                    track: true,
                    date: '2020-07-01',
                },
            },
        };

        expect(() => validate(settings)).not.toThrow();
    });

    test('plugin array', () => {
        const settings = {
            plugins: [
                () => ({}),
            ],
        };

        expect(() => validate(settings)).not.toThrow();
    });

    test('plugin factory', () => {
        const settings = {
            plugins: () => [],
        };

        expect(() => validate(settings)).not.toThrow();
    });
});
Example #29
Source File: resizing.test.ts    From obsidian-imgur-plugin with MIT License 4 votes vote down vote up
describe("resizeTo", () => {
  it.each([
    {
      input: "![](https://i.imgur.com/m3RpPCVm.png)",
      size: ImgurSize.SMALL_SQUARE,
      output:
        "[![](https://i.imgur.com/m3RpPCVs.png)](https://i.imgur.com/m3RpPCV.png)",
    },
    {
      input: "![](https://i.imgur.com/m3RpPCVm.png)",
      size: ImgurSize.BIG_SQUARE,
      output:
        "[![](https://i.imgur.com/m3RpPCVb.png)](https://i.imgur.com/m3RpPCV.png)",
    },
    {
      input: "![](https://i.imgur.com/m3RpPCVm.png)",
      size: ImgurSize.SMALL_THUMBNAIL,
      output:
        "[![](https://i.imgur.com/m3RpPCVt.png)](https://i.imgur.com/m3RpPCV.png)",
    },
    {
      input: "![](https://i.imgur.com/m3RpPCVm.png)",
      size: ImgurSize.MEDIUM_THUMBNAIL,
      output:
        "[![](https://i.imgur.com/m3RpPCVm.png)](https://i.imgur.com/m3RpPCV.png)",
    },
    {
      input: "![](https://i.imgur.com/m3RpPCVm.png)",
      size: ImgurSize.LARGE_THUMBNAIL,
      output:
        "[![](https://i.imgur.com/m3RpPCVl.png)](https://i.imgur.com/m3RpPCV.png)",
    },
    {
      input: "![](https://i.imgur.com/m3RpPCVm.png)",
      size: ImgurSize.HUGE_THUMBNAIL,
      output:
        "[![](https://i.imgur.com/m3RpPCVh.png)](https://i.imgur.com/m3RpPCV.png)",
    },
  ])("resizes an image to '$size' as expected", ({ input, size, output }) => {
    const match = imgurMarkdownImageRegexMatch(input, 0);
    const replacement = resizeTo(size)(match.mdImagePieces).content;

    expect(replacement).toBe(output);
  });

  it("can resize already resized image", () => {
    const smallThumbnail =
      "[![](https://i.imgur.com/m3RpPCVt.png)](https://i.imgur.com/m3RpPCV.png)";
    const match = imgurMarkdownImageRegexMatch(smallThumbnail, 0);
    const replacement = resizeTo(ImgurSize.LARGE_THUMBNAIL)(
      match.mdImagePieces
    ).content;

    expect(replacement).toBe(
      "[![](https://i.imgur.com/m3RpPCVl.png)](https://i.imgur.com/m3RpPCV.png)"
    );
  });

  it("provides correct range to be replaced", () => {
    const originalImage = "   ![](https://i.imgur.com/m3RpPCV.png)";
    const match = imgurMarkdownImageRegexMatch(originalImage, 3);
    const replacement = resizeTo(ImgurSize.LARGE_THUMBNAIL)(
      match.mdImagePieces
    );

    expect(replacement.from).toBe(3);
    expect(replacement.to).toBe(39);
  });

  it.each([
    {
      input:
        "[![](https://i.imgur.com/m3RpPCVs.png)](https://i.imgur.com/m3RpPCV.png)",
      inputDescription: "wrapped resized image",
    },
    {
      input: "![](https://i.imgur.com/m3RpPCVm.png)",
      inputDescription: "resized image",
    },
  ])("resizes '$inputDescription' to original size", ({ input }) => {
    const match = imgurMarkdownImageRegexMatch(input, 0);
    const replacement = resizeTo(ImgurSize.ORIGINAL)(
      match.mdImagePieces
    ).content;

    expect(replacement).toBe("![](https://i.imgur.com/m3RpPCV.png)");
  });
});