javascript - 松露 JS 测试不起作用
问题描述
我在 Truffle 框架中有一个可靠的合同,我无法弄清楚为什么我的 JS 测试不起作用。
我正在尝试测试“setPlayers”函数,合同有效并且测试正在运行,但我不明白如何在测试中调用该函数:
pragma solidity ^0.4.23;
contract Swindle {
string public eventName;
uint public entryFee;
string[] public players;
string public winner;
uint public winnings;
function comp(string _eventName, uint _entryFee) public {
eventName = _eventName;
entryFee = _entryFee;
}
function addPlayers(string _player) public {
players.push(_player);
}
function winner(string _player) public returns (string, uint) {
winner = _player;
winnings = (players.length * entryFee);
return (winner, winnings);
}
}
测试文件:
var Swindle = artifacts.require("Swindle");
contract('Swindle', function(accounts) {
it('sets player to stuart', function(){
return Swindle.deployed().then(function(instance) {
swindle = instance;
return swindle.addPlayers.call("stuart");
}).then(function(swindle) {
assert.equal(swindle.players[0], "stuart", "sets the total supply");
})
})
})
错误:
0 passing (302ms)
1 failing
1) Contract: Swindle
sets player to stuart:
TypeError: Cannot read property '0' of undefined
at test/test-swindle.js:10:32
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:118:7)
解决方案
合同中没有setPlayers
您在测试中提到的方法。
您不能直接访问 javascript 中的合同数组。首先你需要调用players
as 方法。
it('sets player to stuart', function(){
return Swindle.deployed().then(function(instance) {
swindle = instance;
return swindle.addPlayers.call("stuart");
}).then(function(swindle) {
return swindle.players();
}).then(function(players) {
assert.equal(players[0], "stuart", "sets the total supply");
})
})
您可以async/await
提高测试的可读性。
it('sets player to stuart', async () => {
let swindle = await Swindle.deployed();
await swindle.addPlayers.call("stuart");
let players = await swindle.players.call();
assert.equal(players[0], "stuart", "sets the total supply");
});
推荐阅读
- c++ - Armadillo C++ 配置检查
- python - fast_executemany=True 等效于 SQLALCHEMY 中的 Oracle
- java - 为什么我们不能只抛出 Exception/Throwable 而不是有多个异常
- pytorch - 使用卷积自动编码器在照片上添加微笑的问题
- html - 如何在左侧垂直对齐多个div,在右侧垂直对齐一个大div?
- android - 无法解析所有配置文件:':app:debugRuntimeClasspath'
- c++ - 如何使用 Miracl c++ 实现双线性配对
- javascript - 为什么创建Vue组件时我的数组未定义?
- r - 具有目标“计数:泊松”的 xgboost 模型上的 R 中的 LIME
- javascript - 如何在 django 中创建和使用变量