以前我有 Jest 代码来测试非安全 cookie 的值。它看起来像这样:expect(Cookie.get('myToken')).toBe('tokenvalue');
(本例中的 Cookie
使用的是 js-cookie
api)
但是,我尝试更新我设置 cookie 的方式,并添加了 secure
标志并将其设置为 true
.当测试运行时,Jest 不再能看到这个 cookie。
测试它的最佳方法是什么?
我看过类似 Jest secure cookies? 的问题
我还测试了代码并在浏览器中检查了设置了安全标志。所以这只是一个测试问题。我设置 cookie 的代码如下所示:
Cookie.set('myToken', values.user.token, {
path: '/',
expires: new Date(new Date().getTime() + TOKEN_DURATION),
secure: true
});
最佳答案
我在下面试过,它奏效了
import { * as cookies } from <...ur file where cookie logic is implementated>
import Cookies from 'js-cookie';
describe('cookies functionality', () => {
it('should set the cookie correctly', () => {
// create a mock function using jest.fn()
const mockSet = jest.fn();
// here we are trying to mock the 'set' functionality of Cookie
Cookies.set = mockSet;
// call the set method of Cookies
cookies.set('key', 'value');
// check if the mock function gets called here
expect(mockSet).toBeCalled();
});
});
基本上,编写单元测试是为了测试我们正在测试的单元的逻辑。如果我们使用任何外部库,那么我们可以模拟它并测试它是否被正确调用。单元测试不应该关心该库代码的实际执行,在我们这里的例子中,我们不应该在我们的单元测试中关心 Cookie 真正设置数据。如果我们可以测试 cookie 的 set/get 是否被调用,那么它应该足够好了。
关于cookies - 使用 Jest 测试安全 cookie 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55974032/