我正在尝试测试 makeRandomComputerMove 函数,但是,我无法使用 Jest 正确模拟从同一模块导出的 getRandomNumber 函数。
如果我直接在测试文件中调用 getRandomNumber 函数,它会按预期工作,但我的印象是,模拟测试文件中的函数应该强制内部 makeRandomComputerMove 函数使用模拟值。
如有任何帮助,我们将不胜感激。
测试.ticTacToe.js
describe('TicTacToe Utils', () => {
const randomMock = jest.spyOn(Utils, 'getRandomNumber')
.mockReturnValueOnce(0)
.mockReturnValueOnce(1)
const board = [
[['X'], [], []],
[[], [], []],
[[], [], []]
]
it('makeRandomComputerMove', () => {
const location = Utils.makeRandomComputerMove(board)
// expect(location.x).toBe(0)
// expect(location.y).toBe(1)
})
})
ticTacToe.js
export const getRandomNumber = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
export const makeRandomComputerMove = (board) => {
const location = {};
location.x = getRandomNumber(0, board.length - 1);
location.y = getRandomNumber(0, board.length - 1);
if (location.x < 3 && location.y < 3) {
return location
}
return makeRandomComputerMove(board);
};
最佳答案
你将无法 mock getRandomNumber
当它被 makeRandomComputerMove
调用时在同一个文件中。
相反,您可以移动 getRandomNumber
到一个单独的文件,然后可以对其进行模拟:
getRandomNumber.js
export const getRandomNumber = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
ticTacToe.js
import { getRandomNumber } from './getRandomNumber';
export const makeRandomComputerMove = (board) => {
const location = {};
location.x = getRandomNumber(0, board.length - 1);
location.y = getRandomNumber(0, board.length - 1);
if (location.x < 3 && location.y < 3) {
return location
}
return makeRandomComputerMove(board)
}
test.ticTacToe.js
import Utils from './'
import { getRandomNumber } from './getRandomNumber'
jest.mock('./getRandomNumber', () => ({
getRandomNumber: jest.fn()
}))
describe('TicTacToe Utils', () => {
getRandomNumber.mockReturnValueOnce(0)
getRandomNumber.mockReturnValueOnce(1)
const board = [
[['X'], [], []],
[[], [], []],
[[], [], []]
]
it('makeRandomComputerMove', () => {
const location = Utils.makeRandomComputerMove(board)
expect(location.x).toBe(0)
expect(location.y).toBe(1)
})
})
我希望这会有所帮助。
关于javascript - 开 Jest : How to I test a function that calls another function in the body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60386682/