javascript - 如何模拟 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);
});
});
对于所有测试,我得到“令牌”,但我想在单个测试中将令牌更改为空
解决方案
使用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);
});
});
推荐阅读
- qt - 如何从命令行选择 VLC QT 接口配置文件
- python - 在 Keras 中集成多个模型预测触发回溯警告
- db2 - SQL 错误:
在使用它的上下文中无效。如何在 DB2 数据库的持久性文件中设置 maxColumnNameLength 属性? - swift - 从每米秒数快速获取每公里分钟数
- r - 将几行空行添加到 R 中的数据框中的最优雅方法?
- python - Python生成器让我困惑
- c# - 命名txt文件
- java - 嵌入式模式下的 Apache Drill sqlline 在 Ubuntu 18.04 上崩溃
- java - 关于 Java 中带有 System.out.print 的运算符的问题
- javascript - 如何将 className 添加到自定义组件的包装器中