簡體   English   中英

使用 Jest 測試 3rd 方模塊內的匿名函數

[英]Using Jest to test anonymous function inside 3rd party module

我有一個非常簡單的模塊,它使用pgnode-postgre lib)模塊,我想實現一個 Jest 測試,在模擬pg模塊時,我想運行它的回調函數來查看console.log運行和我的回調正在被調用

我嘲笑了該模塊並試圖監視並替換“查詢”方法,但它失敗並被粉碎了,知道我做錯了什么嗎?

考試科目:

import {Pool} from 'pg';

const pool = new Pool();

module.exports = {
  query: (text, params, callback) => {
    const start = Date.now();

    return pool.query(text, params, (err, res) => {
      const duration = Date.now() - start;
      console.log('executed query', {text, duration, rows: res.rowCount});
      callback(err, res);
    });
  }
};

測試:

jest.mock('pg');

import module from './index';
import { Pool } from 'pg'

beforeAll(() => {
  Pool.mockImplementation(()=>{return jest.fn()});
});


  it('callback is called', () => {
    const cb = (err, res) => true;
    const query = jest.spyOn(Pool, "query");         // <---- Not right, Error
    query.mockImplementation((a,b,c) => c({},{}));
    const resolve = module.query('QUERY TEXT', { a: 1, b: 2}, cb);
    resolve();                                       // <---- Not what I expect
    expect(cb).toBeCalled();
  });
});

拋出錯誤:錯誤:無法監視查詢屬性,因為它不是函數; 給出未定義

  20 |   it('callback is called', () => {
  21 |     const cb = (err, res) => true;
> 22 |     const query = jest.spyOn(Pool, "query");
     |                        ^
  23 |     query.mockImplementation((a,b,c) => c({},{}));
  24 |     const resolve = module.query('QUERY TEXT', { a: 1, b: 2}, cb);
  25 |     resolve();

  at ModuleMockerClass.spyOn (node_modules/jest-mock/build/index.js:697:15)
  at Object.spyOn (src/db/index.test.js:22:24)

謝謝

這是單元測試解決方案:

index.js

import { Pool } from 'pg';
const pool = new Pool();

module.exports = {
  query: (text, params, callback) => {
    const start = Date.now();

    return pool.query(text, params, (err, res) => {
      const duration = Date.now() - start;
      console.log('executed query', { text, duration, rows: res.rowCount });
      callback(err, res);
    });
  }
};

index.spec.js

import mod from '.';
import { Pool } from 'pg';

jest.mock('pg', () => {
  const mPool = {
    query: jest.fn()
  };
  return { Pool: jest.fn(() => mPool) };
});

const pool = new Pool();

afterEach(() => {
  jest.resetAllMocks();
  jest.restoreAllMocks();
});

it('callback is called', done => {
  let queryCallback;
  pool.query.mockImplementation((text, params, callback) => {
    queryCallback = callback;
  });
  const logSpy = jest.spyOn(console, 'log');
  const userCallback = jest.fn();
  mod.query('text', 'params', userCallback);
  const mRes = { rowCount: 1 };
  queryCallback(null, mRes);
  expect(pool.query).toBeCalledWith('text', 'params', queryCallback);
  expect(userCallback).toBeCalledWith(null, mRes);
  expect(logSpy).toBeCalledWith('executed query', { text: 'text', duration: expect.any(Number), rows: 1 });
  done();
});

100% 覆蓋率的單元測試結果:

 PASS  src/stackoverflow/52831401/index.spec.js
  ✓ callback is called (15ms)

  console.log node_modules/jest-mock/build/index.js:860
    executed query { text: 'text', duration: 0, rows: 1 }

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.js |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.026s

源代碼: https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/52831401

暫無
暫無

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

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