// Arup Guha
// 4/13/2020
// Alternate Solution to COP 4516 Team Final Contest Problem: Building Bubblers (uses Prim's)

import java.util.*;

public class bubblers_arup_prims {

	public static void main(String[] args) {

		Scanner stdin = new Scanner(System.in);
		int nC = stdin.nextInt();
		
		// Process all cases.
		for (int loop=0; loop<nC; loop++) {
		
			int n = stdin.nextInt();
			int e = stdin.nextInt();
			
			// Read in edges.
			ArrayList<ArrayList<edge>> eList = new ArrayList<ArrayList<edge>>();
			for (int i=0; i<n; i++) eList.add(new ArrayList<edge>());
			
			for (int i=0; i<e; i++) {
				int u = stdin.nextInt()-1;
				int v = stdin.nextInt()-1;
				int t = stdin.nextInt();
				eList.get(u).add(new edge(u,v,t));
				eList.get(v).add(new edge(v,u,t));
			}
			
			// Will store times edges become available here.
			int[] times = new int[n-1];
			
			// PQ for Prims
			PriorityQueue<edge> pq = new PriorityQueue<edge>();
			boolean[] used = new boolean[n];
			used[0] = true;
			int idx = 0;
			
			// Edges we can choose from at first.
			for (edge x: eList.get(0))
				pq.offer(x);
			
			// Go until we have the right number of edges or we run out of edges.
			while (idx < n-1 && pq.size() > 0) {
			
				// Get the next edge.
				edge cur = pq.poll();
				
				// We've already connected to v.
				if (used[cur.v]) continue;
				
				// Add edge, update pq.
				times[idx++] = cur.w;
				used[cur.v] = true;
				
				// Add in all of cur.v's neighbors.
				for (edge x: eList.get(cur.v))
					pq.offer(x);
			}
			
			// No MST at all...
			if (idx < n-1)
				System.out.println(-1);
		
			// We have to calculate our finish time.
			else {
			
				int curT = 0;
				
				// Since we used Prim's these may not be sorted!!!
				Arrays.sort(times);				
				
				// Either we wait till the edge is available, or
				// we are busy and get to this as soon as we are ready.
				for (int i=0; i<n-1; i++) {
					curT = Math.max(curT, times[i])+1;
				}
				
				// When we finish.
				System.out.println(curT);
			}
		}	
	}
}

// Edge class
class edge implements Comparable<edge> {

	public int u;
	public int v;
	public int w;
	
	public edge(int myu, int myv, int myw) {
		u = myu;
		v = myv;
		w = myw;
	}
	
	public int compareTo(edge other) {
		return w - other.w;
	}
}