簡體   English   中英

在 Jest 中為 es6 類的靜態方法創建模擬實現

[英]Create mockImplementation for es6 Class' Static Method in Jest

我正在測試一個函數,該函數在其中調用來自(es6 類)控制器的靜態方法,該方法返回 API 獲取的結果。 由於我正在編寫單元測試並且控制器有自己的測試,因此我想模擬(技術上偽造)類中的靜態方法,以便為我提供不同類型的響應。

// Controller.js
class Controller {
  static async fetchResults() {} // the method I want to fake
}
// func.js - the function I am writing the test for
const func = async (ctx) => {
  const data = await Controller.fetchResults(ctx.req.url)

  if (containsErrors(data)) ... // do some logic

  return { ...data, ...otherStuff }
}

這種偽造static async fetchResults()的嘗試沒有任何作用,測試嘗試調用原始控制器的fetchResults方法。

// func.test.js
describe('when data is successfuly fetched', () => {
  jest.mock('./Controller.js', () => jest.fn().mockImplementation(() => ({
    fetchResults: jest.fn(() => mockResponse),
  });

  it('returns correct information', async () => {
    expect(await func(context)).toEqual({ ...mockResponse, ...otherStuff });
  });
});

下一次嘗試似乎模擬在某種程度上起作用了,但返回的值是undefined而不是{ ...mockResponse, ...otherStuff }這表明整個類都被fetchResults了,但由於找不到fetchResults它是一個static方法而不是一個實例方法。

import Controller from './Controller.js'

describe('when data is successfuly fetched', () => {
  Controller.mockImplementation(jest.fn(() => ({
    fetchHotel: () => { ...mockResponse, ...otherStuff }
  })

  it('returns correct information', async () => {
    expect(await func(context)).toEqual({ ...mockResponse, ...otherStuff });
  });
});

您可以使用jest.spyOn(object, methodName)來做到這一點。

例如

controller.js

export class Controller {
  static async fetchResults(url) {
    return { result: 'real result' };
  }
}

func.js

import { Controller } from './controller';

const func = async (ctx) => {
  const data = await Controller.fetchResults(ctx.req.url);
  // do some logic
  return { ...data };
};

export { func };

func.test.js :

import { Controller } from './controller';
import { func } from './func';

describe('60776211', () => {
  it('should pass', async () => {
    const fetchResultsSpy = jest.spyOn(Controller, 'fetchResults').mockResolvedValueOnce({ result: 'fake data' });
    const ctx = { req: { url: 'example.com' } };
    const actual = await func(ctx);
    expect(actual).toEqual({ result: 'fake data' });
    fetchResultsSpy.mockRestore();
  });
});

帶有覆蓋率報告的單元測試結果:

 PASS  stackoverflow/60776211/func.test.ts
  60776211
    ✓ should pass (5ms)

---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------|---------|----------|---------|---------|-------------------
All files      |   91.67 |      100 |      75 |   88.89 |                   
 controller.ts |      80 |      100 |      50 |      75 | 3                 
 func.ts       |     100 |      100 |     100 |     100 |                   
---------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.922s, estimated 11s

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM