首页 > 解决方案 > 如何模拟 js-cookie 和 jwt-decode 以根据测试更新其值

问题描述

我正在尝试测试一个调用 js-cookie 以从 Cookie 中检索信息的函数,然后在该值存在时尝试对其进行解码。我想根据测试更新 cookie 的值,但是这种方法我必须在顶部更新 js-cookie 的值。


import { isLoggedInVar } from 'cache';

jest.mock('js-cookie', () => {
  return {
    get: jest.fn(() => {
      return 'token';
    }),
  };
});

jest.mock('jwt-decode', () => () => ({ exp: 10 }));

describe('isLoggedIn', () => {
  beforeEach(() => {
    isLoggedInVar();
  });

  it('should return false', () => {
    expect(isLoggedInVar()).toEqual(false); // this always returns true as "token" is set for ALL the tests
  });


  it('should return true', () => {
    expect(isLoggedInVar()).toEqual(true);
  });
});

对于所有测试,我得到“令牌”,但我想在单个测试中将令牌更改为空

标签: javascriptdomcookiesjestjsmocking

解决方案


使用jest.doMock是您可能需要的。这允许您在级别上进行模拟,但请记住,在模拟之前test不要测试模块。import/require

这是基于您的代码的示例:

describe('isLoggedIn', () => {
  it('should return false', () => {

    jest.doMock('js-cookie', () => {
      return {
        get: jest.fn(() => {
          return null;
        }),
      };
    });    
    jest.doMock('jwt-decode', () => () => ({ exp: 10 }));
    
    // We `require` in sync function we want to test after having mock set
    const { isLoggedInVar } = require('cache');
    
    expect(isLoggedInVar()).toEqual(false); // this always returns true as "token" is set for ALL the tests
  });


  it('should return true', () => {
    jest.doMock('js-cookie', () => {
      return {
        get: jest.fn(() => {
          return 'token';
        }),
      };
    });    
    jest.doMock('jwt-decode', () => () => ({ exp: 10 }));
    
    const { isLoggedInVar } = require('cache');
    
    expect(isLoggedInVar()).toEqual(true);
  });
});

如果您不想使用require关键字,可以按照上面的链接使用 esmodule 语句import

如果不想使用doMock

您可以在不提供工厂的情况下模拟整个模块,但我们会在每个测试中提供如下所示:

import { isLoggedInVar } from 'cache';
import { get } from 'js-cookie';

jest.mock('js-cookie');

describe('isLoggedIn', () => {  

  it('should return false', () => {
    get.mockReturnValue(null)
    isLoggedInVar();
    expect(isLoggedInVar()).toEqual(false);
  });

  it('should return true', () => {
    get.mockReturnValue('token')
    isLoggedInVar();
    expect(isLoggedInVar()).toEqual(true);
  });
});


推荐阅读