溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Jest框架中的自定義測(cè)試匹配器

發(fā)布時(shí)間:2024-08-28 11:33:48 來(lái)源:億速云 閱讀:80 作者:小樊 欄目:編程語(yǔ)言

在 Jest 框架中,你可以創(chuàng)建自定義測(cè)試匹配器來(lái)滿足特定的測(cè)試需求

  1. 首先,在項(xiàng)目根目錄下創(chuàng)建一個(gè)名為 customMatchers.ts(或 .js)的文件。這將包含我們的自定義測(cè)試匹配器實(shí)現(xiàn)。

  2. 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 };
};
  1. 接下來(lái),我們需要將自定義測(cè)試匹配器添加到 Jest 的全局 expect 對(duì)象中。在項(xiàng)目根目錄下創(chuàng)建一個(gè)名為 setupTests.ts(或 .js)的文件,并添加以下內(nèi)容:
// setupTests.ts
import { toBeWithinRange } from './customMatchers';

expect.extend({
  toBeWithinRange,
});
  1. 確保在 jest.config.js 文件中引用了 setupTests.ts 文件。如果你沒(méi)有這個(gè)文件,請(qǐng)創(chuàng)建一個(gè)并添加以下內(nèi)容:
// jest.config.js
module.exports = {
  // ...其他配置
  setupFilesAfterEnv: ['./setupTests.ts'],
};
  1. 現(xiàn)在,你可以在測(cè)試文件中使用自定義的 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è)試文件中使用它。

向AI問(wèn)一下細(xì)節(jié)

免責(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)容。

AI