Using try! instead of try in the call to jsonObject(with:options:), you tell the compiler: trust me on this: this method will never fail. Let's write a test that feeds in wrong data and asserts that an error is thrown:
func test_Login_WhenJSONIsInvalid_ReturnsError() {
mockURLSession = MockURLSession(data: Data(),
urlResponse: nil,
error: nil)
sut.session = mockURLSession
let errorExpectation = expectation(description: "Error")
var catchedError: Error? = nil
sut.loginUser(withName: "Foo", password: "Bar") { (token, error) in
catchedError = error
errorExpectation.fulfill()
}
waitForExpectations(timeout: 1) { (error) in
XCTAssertNotNil(catchedError)
}
}
In the test, you feed an empty data object to the completion...