Итак, это не полностью сформированная статья, а просто краткое руководство для тех, кто проходит через то же самое, что и я.
Проблема
При попытке добавить простую спецификацию функции с помощью Jest я застрял, пытаясь смоделировать функцию, на которую ссылались в том же файле (получал такие ошибки, как «только для чтения», «не определено» и т. д.):
// Simplified for clarity export function getOrderTotal(order) { ... } export function getTotal(orders) { let total = orders.reduce((accumulator, order) => { return accumulator + parseFloat(getOrderTotal(order)) }, 0) ... return total }
Я только хотел проверить getTotal
, но getOrderTotal
мешал.
Решение
Я использовал babel-plugin-rewire (https://github.com/speedskater/babel-plugin-rewire).
Добавить пряжу:
yarn add babel-plugin-rewire
Добавить подключаемый модуль перенастройки:
// .babelrc module.exports = { presets: ['@vue/app'], plugins: ['@babel/plugin-syntax-dynamic-import'], env: { test: { presets: ['@vue/app'], plugins: ['@babel/plugin-syntax-dynamic-import', 'rewire'] } } }
Файл спецификации:
import { __RewireAPI__, getTotal } from '@/assets/js/order-helper' describe('getTotal', () => { const orders = [{}, {}] // two empty orders // this allows mocking of a function within the same module const getOrderTotalMock = jest.fn().mockReturnValue(100) __RewireAPI__.__Rewire__('getOrderTotal', getOrderTotalMock) describe('when discount is not supplied', () => { it('returns the total', () => { const result = getTotal(orders) ... }) )} })
Мы используем Vue и ES6 (и, следовательно, Babel).
Благодаря:
https://github.com/facebook/jest/issues/936
https://medium.com/@qjli/how-to-mock-specific-module-function-in-jest-715e39a391f4
https://stackoverflow.com/questions/45111198/how-to-mock-functions-in-the-same-module-using-jest