gpt4 book ai didi

javascript - 开 Jest ReferenceError : Cannot access '' before initialization

转载 作者:行者123 更新时间:2023-12-03 23:33:34 27 4
gpt4 key购买 nike

我收到错误:ReferenceError: Cannot access 'myMock' before initialization尽管我尊重关于吊装的开 Jest 文件:
A limitation with the factory parameter is that, since calls to jest.mock() are hoisted to the top of the file, it's not possible to first define a variable and then use it in the factory. An exception is made for variables that start with the word 'mock'.
我正在这样做:

import MyClass from './my_class';
import * as anotherClass from './another_class';

const mockMethod1 = jest.fn();
const mockMethod2 = jest.fn();
jest.mock('./my_class', () => {
return {
default: {
staticMethod: jest.fn().mockReturnValue(
{
method1: mockMethod1,
method2: mockMethod2,
})
}
}
});
正如您所看到的,我的两个变量都尊重“标准”,但没有正确提升。
我错过了什么吗?
显然,当我通过 jest.fn() 时它会起作用而不是我的变量,但我不确定以后如何在我的测试中使用这些。

最佳答案

上面的答案都没有解决我的问题,所以这是我的解决方案:

var mockMyMethod: jest.Mock;

jest.mock('some-package', () => ({
myMethod: mockMyMethod
}));
在导入之前使用 const 对我来说感觉很奇怪。事情是: jest.mock被吊起。为了能够在变量之前使用它,您需要使用 var ,因为它也被吊起。它不适用于 letconst因为他们不是。

关于javascript - 开 Jest ReferenceError : Cannot access '' before initialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65554910/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com