我对 jest 进行了测试,只是为了开始测试 react 组件ץ
我花了一段时间才明白,出于某种原因,我的 jest.mock
函数没有影响子组件
所以我做了一个快速测试:
我已经创建了组件 b.tsx
import React from "react";
export default function B({testProp: string}) {
return (
<div className="B">
not printed
</div>
);
}
和调用它的组件a
import React from "react";
import B from "./b";
export default function App() {
return (
<div className="App">
<B testProp="mocking"/>
</div>
);
}
然后我为 a 创建了一个模拟 b 的测试类
import React from 'react';
import { render } from '@testing-library/react';
import App from './a';
describe('render', () => {
beforeEach(() => {
jest.mock('./b', () => ({ testProp }) => <div>A mock with '{testProp}' passed!</div>);
})
it('renders', () => {
const { container } = render(<App/>);
expect(container.textContent)
.toMatch(`A mock with 'mocking' passed!`);
});
})
但是失败了
所以我已经将模拟移到了 describe 函数之外:
import React from 'react';
import { render } from '@testing-library/react';
import App from './a';
jest.mock('./b', () => ({ testProp }) => <div>A mock with '{testProp}' passed!</div>);
describe('render', () => {
it('renders', () => {
const { container } = render(<App/>);
expect(container.textContent)
.toMatch(`A mock with 'mocking' passed!`);
});
})
现在它通过了ץ
我找不到 jest 的文档或关于它失败原因的反应测试库信息,我在其他问题中看到的所有示例都只是假设而没有解释。
你知道是什么导致了这种行为吗?