简体   繁体   中英

How to do unit testing of function which is depends on another function using karma jasmine

I want to test getTokenExpirationDate() method which uses other method jwt_decode and it is imported from jwt-decode. How I can do unit testing for this method?. How This jwt_decode method can be mocked.

import { Injectable } from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import * as jwt_decode from 'jwt-decode';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) { }

  canActivate(): boolean {
    const token = localStorage.getItem(('loginToken'));
    if (this.isTokenExpired(token)) {
      localStorage.removeItem('loginToken');
      this.router.navigate(['/login']);
      return false;
    } else {
      return true;
    }
  }

  isTokenExpired(token: string): boolean {
    if (!token) { return true;
    } else {
      const date = this.getTokenExpirationDate(token);
      if (date === undefined) {
        return false;
      } else {
        return !(date.valueOf() > new Date().valueOf());
      }
    }
  }

  getTokenExpirationDate(token: string): Date {
    const decoded = jwt_decode(token);
    if (decoded.exp === undefined) {
      return null;
    } else {
      const date = new Date(0);
      date.setUTCSeconds(decoded.exp);
      return date;
    }
  }

}

You don't mock jwt_decode . You only write test for getTokenExpirationDate .

jwt_decode is an internal call of your public function. You test it implicitly by writing test cases for getTokenExpirationDate .

It appears to be a pure function without sideeffects that you can safely use and your behavior of your method will remain consistent.

Use it, don't mock it or write unit tests for it. Test your business logic, not your dependencies.


And jwt_decode already has unit tests: https://github.com/auth0/jwt-decode/blob/master/test/tests.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM