Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/444.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 如何模拟js cookie和jwt解码以基于测试更新其值_Javascript_Dom_Cookies_Jestjs_Mocking - Fatal编程技术网

Javascript 如何模拟js cookie和jwt解码以基于测试更新其值

Javascript 如何模拟js cookie和jwt解码以基于测试更新其值,javascript,dom,cookies,jestjs,mocking,Javascript,Dom,Cookies,Jestjs,Mocking,我正在测试一个函数,该函数调用js cookie从cookie中检索信息,然后尝试解码该值是否存在。我想根据测试更新cookie的值,但这种方法必须在顶部更新js cookie的值 import { isLoggedInVar } from 'cache'; jest.mock('js-cookie', () => { return { get: jest.fn(() => { return 'token'; }), }; }); jest.

我正在测试一个函数,该函数调用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);
  });
});
对于所有的测试,我都会得到“token”,但我想在单个测试中将token更改为空,这是您可能需要的。这允许您在
test
级别进行模拟,但请记住,在模拟测试模块之前,不要导入/要求它

以下是基于您的代码的示例:

description('isLoggedIn',()=>{
它('应该返回false',()=>{
jest.doMock('js-cookie',()=>{
返回{
get:jest.fn(()=>{
返回null;
}),
};
});    
doMock('jwt-decode',()=>()=>({exp:10}));
//我们需要在模拟设置后测试同步函数中的'require'
const{isLoggedInVar}=require('cache');
expect(isLoggedInVar()).toEqual(false);//当为所有测试设置了“token”时,它总是返回true
});
它('应该返回true',()=>{
jest.doMock('js-cookie',()=>{
返回{
get:jest.fn(()=>{
返回“令牌”;
}),
};
});    
doMock('jwt-decode',()=>()=>({exp:10}));
const{isLoggedInVar}=require('cache');
expect(isLoggedInVar()).toEqual(true);
});
});
如果您不想使用
require
关键字,您可以按照上面的链接使用esmodule语句
import

如果热衷于不使用doMock: 您可以在不提供工厂的情况下模拟整个模块,但我们会在每个测试中提供如下内容:

从“缓存”导入{isLoggedInVar};
从“js cookie”导入{get};
mock('js-cookie');
描述('isLoggedIn',()=>{
它('应该返回false',()=>{
get.mockReturnValue(null)
isLoggedInVar();
expect(isLoggedInVar()).toEqual(false);
});
它('应该返回true',()=>{
get.mockReturnValue('token')
isLoggedInVar();
expect(isLoggedInVar()).toEqual(true);
});
});

将jest.fn()移动到jest.mock调用之外,以便您可以执行例如
getCookie.mockReturnValue('othertoken')
?最简单的方法是让Jest自动模拟模块,但不通过模拟实现,然后您可以在测试中导入模拟,就像在测试代码中导入模拟一样。@jonrsharpe您能举个例子说明它可以工作吗
constgetmock=jest.fn(()=>{returnnull;});doMock('js-cookie',()=>{return{get:getMock(),};});doMock('jwt-decode',()=>()=>({exp:10}))