您好,登錄后才能下訂單哦!
在 Jest 框架中,你可以創(chuàng)建自定義測(cè)試匹配器來(lái)滿足特定的測(cè)試需求
首先,在項(xiàng)目根目錄下創(chuàng)建一個(gè)名為 customMatchers.ts
(或 .js
)的文件。這將包含我們的自定義測(cè)試匹配器實(shí)現(xiàn)。
在 customMatchers.ts
文件中,編寫(xiě)一個(gè)自定義測(cè)試匹配器函數(shù)。例如,我們可以創(chuàng)建一個(gè)名為 toBeWithinRange
的匹配器,用于檢查一個(gè)值是否在指定范圍內(nèi):
// customMatchers.ts
import { matcherHint, printExpected, printReceived } from 'jest-matcher-utils';
const toBeWithinRange = (received: number, floor: number, ceiling: number) => {
const pass = received >= floor && received <= ceiling;
const message = pass
? () =>
`${matcherHint('.not.toBeWithinRange')}\n\n` +
`Expected value not to be within range:\n` +
` floor: ${printExpected(floor)}\n` +
` ceiling: ${printExpected(ceiling)}\n` +
`Received:\n` +
` ${printReceived(received)}`
: () =>
`${matcherHint('.toBeWithinRange')}\n\n` +
`Expected value to be within range:\n` +
` floor: ${printExpected(floor)}\n` +
` ceiling: ${printExpected(ceiling)}\n` +
`Received:\n` +
` ${printReceived(received)}`;
return { message, pass };
};
expect
對(duì)象中。在項(xiàng)目根目錄下創(chuàng)建一個(gè)名為 setupTests.ts
(或 .js
)的文件,并添加以下內(nèi)容:// setupTests.ts
import { toBeWithinRange } from './customMatchers';
expect.extend({
toBeWithinRange,
});
jest.config.js
文件中引用了 setupTests.ts
文件。如果你沒(méi)有這個(gè)文件,請(qǐng)創(chuàng)建一個(gè)并添加以下內(nèi)容:// jest.config.js
module.exports = {
// ...其他配置
setupFilesAfterEnv: ['./setupTests.ts'],
};
toBeWithinRange
匹配器:// myComponent.test.ts
import React from 'react';
import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';
test('renders the correct value', () => {
render(<MyComponent />);
const valueElement = screen.getByText(/Value: /i);
const value = parseInt(valueElement.textContent.split(' ')[1], 10);
expect(value).toBeWithinRange(1, 100);
});
在這個(gè)示例中,我們創(chuàng)建了一個(gè)名為 toBeWithinRange
的自定義測(cè)試匹配器,用于檢查一個(gè)值是否在指定范圍內(nèi)。然后,我們?cè)?setupTests.ts
文件中將其添加到 Jest 的全局 expect
對(duì)象中,并在測(cè)試文件中使用它。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。