嘲笑模块功能

时间:2018-12-06 10:50:20

标签: javascript unit-testing lodash jestjs es6-modules

我正在开玩笑地测试我想监视一些lodash函数,这些函数是我分别导入模块中的(与将整个lodash模块导入为_相反),例如

/** matrix.js **/
import shuffle from 'lodash/shuffle'
import pick from 'lodash/pick'

// ...

/**
 * Shuffles the order of the rows in the matrix. If a column/variable name
 * is specified, only the rows in this column are shuffled.
 *
 * @export
 * @param {array} matrix The matrix to be shuffled
 * @param {array} columns  Array containing the variable/column to be shuffled
 * @returns {array}
 */
export function shuffleVert (matrix, columns) {
  if (typeof (columns) === 'undefined' || (isArray(columns) && columns.length === 0)) {
    return shuffle(matrix)
  } else if (!isArray(columns)) {
    throw new TypeError('Invalid argument for columns specified to shuffleVert. Expects an array containing column names')
  } else {
    let grouped = unstack(matrix)
    let cols = pick(grouped, columns)
    cols = Object.entries(cols).reduce((prev, [key, values]) => {
      prev[key] = shuffle(values)
      return prev
    }, {})
    return stack({ ...grouped, ...cols })
 }

shuffleVert函数可对矩阵的所有行或指定列的所有行进行混洗。据我所知,由于很难用随机输出来测试函数,所以我只想测试被测试函数中是否调用了lodash的shuffle和pick函数。

我目前在我的测试模块中实施了一个有效的间谍程序,但我认为这不是常规的或高效的,我只是认为必须有一种更好的方法来实现此目的...

/* matrix.test.js */
import {
  shuffleVert,
} from 'matrix'

/** Generate a mock functions to spy on lodash */
const mockShuffle = jest.fn()
jest.mock('lodash/shuffle', () => a => {
  const shuffle = jest.requireActual('lodash/shuffle')
  mockShuffle()
  return shuffle(a)
})

const mockPick = jest.fn()
jest.mock('lodash/pick', () => (a, b) => {
  const pick = jest.requireActual('lodash/pick')
  mockPick()
  return pick(a, b)
})

describe('reverseRows', () => {
  let srcMatrix
  beforeEach(() => {
    srcMatrix = [
      { number: 1, word: 'one' },
      { number: 2, word: 'two' },
      { number: 3, word: 'three' }
    ]
    mockShuffle.mockClear()
    mockPick.mockClear()
  })

  it('should shuffle the rows of the entire matrix with no argument for columns', () => {
    shuffleVert(srcMatrix)
    // 2 is weird, but seems correct.
    // It appears the shuffle function calls itself recursively
    expect(mockShuffle).toHaveBeenCalledTimes(2)
  })

  it('should only shuffle the rows of columns that were specified', () => {
    shuffleVert(srcMatrix, ['word'])
    expect(mockShuffle).toHaveBeenCalledTimes(2)
    expect(mockPick).toHaveBeenCalledTimes(2)
  })
})

我知道玩笑具有spyOn功能,但这似乎仅适用于对象方法,因此

import * as lodash from 'lodash'
const shuffleSpy = jest.spyOn(lodash, 'shuffle')

导致错误Cannot spyOn on a primitive value; undefined given

通常,最好的侦听模块方法的最佳方法是什么?是否有更好的实现方式来实现我想要实现的目标?还是这已经走了?

1 个答案:

答案 0 :(得分:0)

请尝试一下,让我知道它是否适合您

import { shuffleVert } from 'matrix';
const shuffleVertRef = {
    shuffleVert
};
let spyShuffleVert;

beforeEach(() => {
    spyShuffleVert = jest.spyOn(shuffleVertRef, "shuffleVert");
}

afterEach(() => {
    jest.clearAllMocks();
}

it('should shuffle the rows of the entire matrix with no argument for columns', () = {
    let srcMatrix = [
        { number: 1, word: 'one' },
        { number: 2, word: 'two' },
        { number: 3, word: 'three' }
    ];

    shuffleVert(srcMatrix);
    expect(spyShuffleVert).toHaveBeenCalledTimes(2);
}

然后,如果您要检查其他函数的执行时间,只需将它们添加到a /那个常量中,然后在下面spyOn处添加它们即可。

我对此也没有足够的了解,但是从我读到的内容来看,最新版本的JavaScript具有称为“单一事实来源”的原则,这是某些事情正常运行所必需的。