繁体   English   中英

具有应模拟的内部函数的测试函数

[英]Testing function with inner function that should be mocked

我在测试此功能时遇到问题。 我不知道在checkAuth decode时如何测试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;
};

我的测试不起作用。 它需要原始功能。

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
  });
});

有人可以向我解释如何解决这个问题吗?

您可以使用jest.mock(moduleName, factory, options)方法来模拟jwt-decode模块。

例如

index.js

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) {
      console.log(123);
      return false;
    }
  } catch (e) {
    console.log(e);
    return false;
  }

  return true;
};

index.spec.js

import decode from 'jwt-decode';
import { checkAuth } from '.';

jest.mock('jwt-decode', () => jest.fn());

const mLocalStorage = {
  _storage: {},
  getItem: jest.fn((key) => {
    return this._storage[key];
  }),
  setItem: jest.fn((key, value) => {
    this._storage[key] = value;
  }),
};
global.localStorage = mLocalStorage;

describe('auth', () => {
  afterEach(() => {
    jest.resetAllMocks();
  });
  it('allows the user to login successfully', async () => {
    localStorage.setItem('token', 'fake_token_user');
    const token = localStorage.getItem('token');

    decode.mockImplementationOnce((token) => {
      return {
        exp: new Date().getTime() / 1000 + 1,
        iat: 1575751766,
        userData: { isAdmin: true, login: 'one92tb', userId: 1 },
      };
    });

    expect(token).toBe('fake_token_user');
    expect(checkAuth()).toBe(true);
  });
});

带有覆盖率报告的单元测试结果:

PASS  src/stackoverflow/59233898/index.spec.js (15.687s)
  auth
    ✓ allows the user to login successfully (11ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |    61.54 |       50 |      100 |    61.54 |                   |
 index.js |    61.54 |       50 |      100 |    61.54 |     6,12,13,16,17 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        17.8s

源代码: https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59233898

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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