我能够成功运行我的测试(在本例中为模拟 i18next.t),而无需指定间谍包装器。为什么?还有什么区别?
基于此处的文档和答案
const spy = jest.spyOn(i18next, 't');
expect(spy).toHaveBeenCalledWith('errorCharacterLength', { min: 5, max: 10 });
expect(result).toEqual(i18next.t('errorCharacterLength', { min: 5, max: 10 }));
如果还能用的话,和这个有什么区别。测试成功。
jest.spyOn(i18next, 't');
expect(i18next.t).toHaveBeenCalledWith('errorCharacterLength', { min: 5, max: 10 });
expect(result).toEqual(i18next.t('errorCharacterLength', { min: 5, max: 10 }));
我不清楚间谍On是否在幕后嘲笑i18next。第二个期望语句意味着什么?
第一个例子应该可以工作。这是将变量设置为间谍的正确方法。变量的值将是一个 Jest 模拟函数,并且您的语法看起来是正确的。第二个起作用的原因是 Jest “猴子修补”了间谍函数,以便
i18next.t
被 Jest 模拟函数替换,该函数也传递到原始函数。由于调用 spyOn
后,t()
方法被 Jest 模拟函数替换,因此您可以针对 expect
调用 i18next.t
断言,因为它现在是 Jest 模拟。