Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用内部函数测试应该模拟的函数_Javascript_Unit Testing_Testing_Mocking_Jestjs - Fatal编程技术网

Javascript 使用内部函数测试应该模拟的函数

Javascript 使用内部函数测试应该模拟的函数,javascript,unit-testing,testing,mocking,jestjs,Javascript,Unit Testing,Testing,Mocking,Jestjs,我在测试这个函数时遇到问题。当解码被模拟时,我不知道如何测试checkAuth import decode from "jwt-decode"; export const checkAuth = () => { const token = localStorage.getItem("token"); if (!token) { return false; } try { const { exp } = decode(token); if (exp

我在测试这个函数时遇到问题。当
解码
被模拟时,我不知道如何测试
checkAuth

import decode from "jwt-decode";

export const checkAuth = () => {
  const token = localStorage.getItem("token");
  if (!token) {
    return false;
  }

  try {
    const { exp } = decode(token);
    if (exp < new Date().getTime() / 1000) {
      return false;
    }
  } catch (e) {
    console.log(e); // 'Invalid token specified: Cannot read property \'replace\' of undefined'
    return false;
  }

  return true;
};
有人能给我解释一下如何解决这个问题吗?

您可以使用这个方法来模拟
jwt解码模块

例如

index.js

从“jwt解码”导入解码;
导出常量checkAuth=()=>{
const token=localStorage.getItem('token');
如果(!令牌){
返回false;
}
试一试{
const{exp}=解码(令牌);
if(exp
index.spec.js

从“jwt解码”导入解码;
从“”导入{checkAuth};
jest.mock('jwt-decode',()=>jest.fn());
常量mLocalStorage={
_存储:{},
getItem:jest.fn((键)=>{
将此返回。_存储器[键];
}),
setItem:jest.fn((键,值)=>{
此._存储[键]=值;
}),
};
global.localStorage=mLocalStorage;
描述('auth',()=>{
之后(()=>{
jest.resetAllMocks();
});
它('允许用户成功登录',异步()=>{
setItem('token','fake_token_user');
const token=localStorage.getItem('token');
decode.mockImplementationOnce((令牌)=>{
返回{
exp:new Date().getTime()/1000+1,
iat:1575751766,
用户数据:{isAdmin:true,登录名:'one92tb',用户ID:1},
};
});
expect(token).toBe('fake_token_user');
expect(checkAuth()).toBe(true);
});
});
单元测试结果和覆盖率报告:

PASS src/stackoverflow/59233898/index.spec.js(15.687s)
认证
✓ 允许用户成功登录(11毫秒)
----------|----------|----------|----------|----------|-------------------|
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s|
----------|----------|----------|----------|----------|-------------------|
所有文件| 61.54 | 50 | 100 | 61.54 ||
index.js | 61.54 | 50 | 100 | 61.54 | 6,12,13,16,17|
----------|----------|----------|----------|----------|-------------------|
测试套件:1个通过,共1个
测试:1项通过,共1项
快照:共0个
时间:17.8秒

源代码:

您希望测试中的常量与另一个文件中的导入有什么关系?我建议你读书。
import { Auth, AuthAdmin, checkAuth, AppContent, AuthApp } from "./Auth";
import LocalStorageMock from "../../../mocks/localStorageMock";
import decode from "jwt-decode";

global.localStorage = new LocalStorageMock();

describe("auth", () => {
  localStorage.setItem("token", "fake_token_user");
  const token = localStorage.getItem("token");

  it("allows the user to login successfully", async () => {
    const decode = jest.fn(token => {
      return {
        exp: new Date().getTime() / 1000 - 1,
        iat: 1575751766,
        userData: { isAdmin: true, login: "one92tb", userId: 1 }
      };
    });
    //const { exp } = decode(token);

    expect(token).toBeDefined();
    expect(checkAuth()).toBe(true) // It runs original decode function
  });
});