我試圖弄清楚為什么我的測驗 - 單獨運行時通過 - 每當描述塊包含超過 1 個測驗時就會失敗。以這個例子為例,我從我的真實代碼中提取并簡化了:
describe('Create Account Form', () => {
const {container} = render(<CreateAccountForm />);
const email = container.querySelector('input[name="email"]');
const password1 = container.querySelector('input[name="password1"]');
it('Should render all fields', () => {
allInputs.forEach((input) => {
expect(input).toBeInTheDocument();
});
});
it('Another test', () => {
expect(email).toBeInTheDocument(); // fails
});
});
第二個測驗失敗,但只有在注釋掉第一個測驗或在測驗中重新渲染容器時才通過,如下所示:
it('Another test', () => {
const {container} = render(<CreateAccountForm />);
const email = container.querySelector('input[name="email"]');
expect(email).toBeInTheDocument(); // passes
});
為什么這必須發生?我寧愿不必重新渲染容器并在每個測驗塊內宣告新變數。
謝謝
uj5u.com熱心網友回復:
afterEachRTL 將卸載在鉤子中使用渲染安裝的 React 樹。請參閱清理。
請注意,如果您使用的測驗框架支持
afterEach全域并將其注入您的測驗環境(如 mocha、Jest 和 Jasmine),這將自動完成。
將render代碼移動到beforeEach單個測驗用例中。這樣我們就可以在每個測驗用例之前創建反應樹。將測驗用例彼此隔離,使用它們自己的測驗資料而不影響其余測驗用例。
例如
index.tsx:
import React from 'react';
export function Example() {
return (
<div>
<input name="email" />
<input name="password1" />
</div>
);
}
index.test.tsx:
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import React from 'react';
import { Example } from './';
describe('70753645', () => {
let email, password1, allInputs;
beforeEach(() => {
const { container } = render(<Example />);
email = container.querySelector('input[name="email"]');
password1 = container.querySelector('input[name="password1"]');
allInputs = container.querySelectorAll('input');
});
it('Should render all fields', () => {
allInputs.forEach((input) => {
expect(input).toBeInTheDocument();
});
});
it('Another test', () => {
expect(email).toBeInTheDocument();
});
});
測驗結果:
PASS stackoverflow/70753645/index.test.tsx (9.222 s)
70753645
? Should render all fields (24 ms)
? Another test (3 ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 9.717 s
包版本:
"@testing-library/react": "^11.2.2",
"jest": "^26.6.3",
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416271.html
標籤:
上一篇:如何在Jest中正確模擬fs.readFileSync()?
下一篇:分離應用程式和包測驗時的匯入問題
