0

Solidity file

pragma solidity ^0.5.0;

contract Todo {

  struct User {
    uint id;
    string name;
  }
  User[] public users;
  uint public nextId = 1;

  function create(string memory name) public {
    users.push(User(nextId, name));
    nextId++;
  }

  function read(uint id) view public returns(uint, string memory) {
    uint i = find(id);
    return(users[i].id, users[i].name);
  }

  function update(uint id, string memory name) public {
    uint i = find(id);
    users[i].name = name;
  }

  function destroy(uint id) public {
    uint i = find(id);
    delete users[i];
  }

  function find(uint id) view internal returns(uint) {
    for(uint i = 0; i < users.length; i++) {
      if(users[i].id == id) {
        return i;
      }
    }
    revert('User does not exist');
  }

}

test file

    const Todo = artifacts.require('Todo');

contract('Todo', () => {
  let todo = null;
  before(async() => {
    todo = await Todo.deployed();
  });

  it('Should create a new user', async () => {
    await todo.create('Kirean');
    const user = await todo.read(1);
    assert(user[0].toNumber() === 1);
    assert(user[1] === 'Kirean');
  });

  it('Should update a user', async () => {
    await todo.update(1, 'Kireannn');
    const user = await todo.read(1);
    assert(user[0].toNumber() === 1);
    assert(user[1] === 'Kireannn');
  });

  it('Should not update a non-existing user', async () =>
  {
    try{
    await todo.update(2, 'Kireannn');
  } catch(e) {
  assert(e.message.includes('user does not exist'));

    return;

  }
  assert(false);
});

it('Should delete a user', async () => {
  await todo.destroy(1);
  try{
    await todo.read(1);
  } catch(e) {
  assert(e.message.includes('user does not exist'));

    return;
  }
  assert(false);
  });

  it('Should not delete a non-existing user', async () => {
    try {
      await todo.destroy(10);
    } catch (e) {
    assert(e.message.includes('user does not exist'));

      return;
  }
  assert(false);
});

});

terminal

0

The array elements start at row 0. This looks suspicious.

 uint public nextId = 1;

Pursuing that a little farther ...

  it('Should create a new user', async () => {
    await todo.create('Kirean');
    const user = await todo.read(1);

You pushed Kirean into row 0 and then tried to access row 1 which is out of range, so the contract reverted.

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.