gpt4 book ai didi

javascript - 将参数传递给 jest.mock

转载 作者:行者123 更新时间:2023-12-03 13:31:42 24 4
gpt4 key购买 nike

我有一个模拟如下

jest.mock('react-hook-inview', () => {
const setRef = jest.fn();
const observer = jest.fn();
const intersecting = true;
const entry = {
y: 0,
};
return [setRef, intersecting, entry, observer];
});

在这里我想更改相交值。我怎样才能将其从一项测试更改为另一项测试?我试图使用类似工厂的东西:

const inView = (intersecting) => {
jest.mock('react-hook-inview', () => {
const setRef = jest.fn();
const observer = jest.fn();
const entry = {
y: 0,
};
return [setRef, intersecting, entry, observer];
});
}

并像这样使用它

  it('is invisible by default', () => {
const text = 'Test';
const { container } = render(<Reveal>{text}</Reveal>);
inView(false);
expect(container.firstChild).not.toBeVisible();
});

it('is visible when in view', () => {
const text = 'Test';
const { container } = render(<Reveal>{text}</Reveal>);
inView(true);
expect(container.firstChild).toBeVisible();
});

但是这会抛出

The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
Invalid variable access: intersecting

有人有想法吗?

干杯!

编辑:

我现在的解决方案是像这样模拟它

import ReactHookInview from 'react-hook-inview';

jest.mock('react-hook-inview', () => ({
useInView: jest.fn().mockImplementation(() => {
const setRef = jest.fn();
const observer = jest.fn();
const intersecting = false;
const entry = {
boundingClientRect: {
y: 0,
},
};
return [setRef, intersecting, entry, observer];
}),
}));

在我的测试中我会这样覆盖:

ReactHookInview.useInView.mockImplementation(() => {
const setRef = jest.fn();
const observer = jest.fn();
const intersecting = true;
const entry = {
boundingClientRect: {
y: 1,
},
};
return [setRef, intersecting, entry, observer];
});

但这并不是很漂亮

最佳答案

您可以像已经完成的那样模拟您的库,导入它并显式设置它的值。然后之前有两组不同的测试:

jest.mock('react-hook-inview', /* as above */ );

import rhi from 'react-hook-inview';

describe('my implementation', () => {

describe('while intersecting', () => {
let result;
beforeAll(() => {
rhi[1] = true;
result = myImplementationUsingIntersecting();
});

it('should result X', () => {
expect(result).toEqual(X);
});
});

describe('while NOT intersecting', () => {
let result;
beforeAll(() => {
rhi[1] = false;
result = myImplementationUsingIntersecting();
});

it.todo('should result Y');
});
})

working example

编辑 2:为了正确模拟 React hook

由于 react 钩子(Hook)是返回内容的函数,因此您可以像这样模拟它

jest.mock('react-hook-inview', () => jest.fn());
// and you can take it's reference with import
import useInView from 'react-hook-inview';
// and then you can mock it's return value as array
beforeAll(() => {
useInView.mockReturnValue(['a', true, 'b', 'c']);
result = myImplementationUsingIntersecting();
})

关于javascript - 将参数传递给 jest.mock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59754803/

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