The method '[]' was called on null Flutter

Viewed 17

I try to make some unit tests on a login funtion in flutter and I have an error that I can't fix.

This is the test:

 test('Register (success)', () async {
    var auth = AuthService();
    var result = await auth.login("test", "123456");
    var json = jsonDecode(result.toString());
    expect(json['success'], true);
  });

This is the function called by the test:

login(name, password) async {
    if (name.toString().isEmpty || password.toString().isEmpty) {
      return "Error: empty field";
    }
     return await dio.post('https://itsmilife.herokuapp.com/authenticate',
        data: {"name": name, "password": password},
        options: Options(contentType: Headers.formUrlEncodedContentType))
  }

This is the function that sent the informations:

    authenticate: function(req, res) {
        User.findOne({
            name: req.body.name
        }, function (err, user) {
            if (err) throw err
            if (!user) {
                res.status(403).send({success: false, msg: 'Authentication Failed, User not found'})
            } else {
                user.comparePassword(req.body.password, function (err, isMatch) {
                    if (isMatch && !err) {
                        var token = jwt.encode(user, config.secret)
                        res.json({success: true, token: token, user: user})
                    }
                    else {
                        return res.status(403).send({success: false, msg: 'Authentication failed wrong password'})
                    }
                })
            }
        })
    },

I have the error when I launch the test:

NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: []("success")
dart:core                    Object.noSuchMethod
test\widget_test.dart 24:16  main.<fn>

I don't understand how to fix the probleme.

1 Answers

Try something like this:

Future<bool> login(name, password) async {
  if (name.toString().isEmpty || password.toString().isEmpty) {
    return false;
  }
  var responseFromServer = await dio.post(
      'https://itsmilife.herokuapp.com/authenticate',
      data: {"name": name, "password": password},
      options: Options(contentType: Headers.formUrlEncodedContentType));

  if (responseFromServer == null || responseFromServer.statusCode != 200) {
    return false;
  }
  return true;
}

Also, make your test like:

test('Register (success)', () async {
    var auth = AuthService();
    var result = await auth.login("test", "123456");
    expect(result, true);
  });
Related