在承诺解决之前完成玩笑测试

发布于 2025-01-09 00:23:41 字数 2472 浏览 0 评论 0原文

这是我在 stackoverflow 上的第一篇文章,所以请保持温柔……

我正在尝试使用 Jest 对与部署在本地开发区块链上的智能合约进行通信的函数进行一些端到端测试。

我遇到的问题可能源于我对 Promise 和事件循环如何工作缺乏透彻的理解,但测试在权益函数完成之前完成。

这是测试:

test('stake', async () => {
        
        let tokenId;
        
        // test set up - make sure the address owns at least 1 NFT
        const currentBalance = (await nftContract.balanceOf(address)).toNumber();
        if (currentBalance > 0) {
            tokenId = (await stakingContractAddress.tokenOfOwnerByIndex(address, 0)).toNumber();
        } else {
            // if address owns no NFTs, mint one
            await mint(address)
        }
        
        // pre stake
        const addressBalance = (await nftContract.balanceOf(address)).toNumber();
        const stakedBalance = (await stakingContractAddress.numStaked(address)).toNumber();

        console.log(`addressBalance: ${addressBalance}`) // should be 1
        console.log(`stakedBalance: ${stakedBalance}`) // should be 0
        
        // stake
        await stake(tokenId, address); // I want this to fully complete before moving on.

        // post stake
        const newAddressBalance = (await nftContract.balanceOf(address)).toNumber();
        const newStakedBalance = (await stakingContractAddress.numStaked(address)).toNumber();

        console.log(`newAddressBalance: ${newAddressBalance}`) // should be 0 but is still 1
        console.log(`newStakedBalance: ${newStakedBalance}`) // should be 1 but is stil 0
        
        expect(newStakedBalance).toEqual(addressBalance);
        expect(newAddressBalance).toEqual(stakedBalance);

    });

这是权益函数:

async function stake(tokenId, _address) {
    try {
        const tx = await nftContract['safeTransferFrom(address,address,uint256,bytes)'](
            _address, // from
            stakingContractAddress, // to
            tokenId,
            gas_price
        );
        await tx.wait(); // this is meant to wait until the transaction is mined on-chain
    } catch (err) {
        logger.info({message: err});
        process.exit(1);
    }
}

我尝试在测试中调用权益函数后立即添加故意等待(如下)。但这没有效果。它还感觉不需要它,因为与本地区块链的交易应该立即完成。

function wait(ms){
    console.log(`waiting ${ms /1000} seconds`)
    var start = new Date().getTime();
    var end = start;
    while(end < start + ms) {
      end = new Date().getTime();
   }
 }

我花了很多时间试图找到解决方案,但没有运气。

任何帮助将不胜感激!

This is my first post on stackoverflow so please be gentle...

I am trying to use Jest to do some end-to-end testing of a function that communicates with a smart contract deployed on a local development blockchain.

The issues I'm having probably stem from my lack of thourough understanding of how promises and the event loop work, but the test completes, before the stake function completes.

Here is the test:

test('stake', async () => {
        
        let tokenId;
        
        // test set up - make sure the address owns at least 1 NFT
        const currentBalance = (await nftContract.balanceOf(address)).toNumber();
        if (currentBalance > 0) {
            tokenId = (await stakingContractAddress.tokenOfOwnerByIndex(address, 0)).toNumber();
        } else {
            // if address owns no NFTs, mint one
            await mint(address)
        }
        
        // pre stake
        const addressBalance = (await nftContract.balanceOf(address)).toNumber();
        const stakedBalance = (await stakingContractAddress.numStaked(address)).toNumber();

        console.log(`addressBalance: ${addressBalance}`) // should be 1
        console.log(`stakedBalance: ${stakedBalance}`) // should be 0
        
        // stake
        await stake(tokenId, address); // I want this to fully complete before moving on.

        // post stake
        const newAddressBalance = (await nftContract.balanceOf(address)).toNumber();
        const newStakedBalance = (await stakingContractAddress.numStaked(address)).toNumber();

        console.log(`newAddressBalance: ${newAddressBalance}`) // should be 0 but is still 1
        console.log(`newStakedBalance: ${newStakedBalance}`) // should be 1 but is stil 0
        
        expect(newStakedBalance).toEqual(addressBalance);
        expect(newAddressBalance).toEqual(stakedBalance);

    });

Here is the stake function:

async function stake(tokenId, _address) {
    try {
        const tx = await nftContract['safeTransferFrom(address,address,uint256,bytes)'](
            _address, // from
            stakingContractAddress, // to
            tokenId,
            gas_price
        );
        await tx.wait(); // this is meant to wait until the transaction is mined on-chain
    } catch (err) {
        logger.info({message: err});
        process.exit(1);
    }
}

I have tried adding in at deliberate wait (below) right after the stake function is called in the test. But this has no effect. It also felt like it shouldn't be needed, as the transaction with the local blockchain should complete instantly.

function wait(ms){
    console.log(`waiting ${ms /1000} seconds`)
    var start = new Date().getTime();
    var end = start;
    while(end < start + ms) {
      end = new Date().getTime();
   }
 }

I've spent so much time trying to find a solution to this already with no luck.

Any help would be greatly appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷你仙 2025-01-16 00:23:41

因此,经过一番思考,我重组了整个应用程序,使其更加模块化和可测试。

最初的应用程序是一个脚本,它确实有效,但不可测试。

除其他外,权益方法现在位于其自己的模块中,我已经能够成功测试该功能。

这个故事的寓意是——编写模块化代码并从一开始就考虑测试。

So after a bit of thought, I restructured the entire application to make it more modular and testable.

The inital application was a single script, which did work but was not testable.

The stake method, among others, is now in its own module and I have been able to successfully test the functionalion.

Moral of this story - Write modular code and think about testing from the start.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文