gpt4 book ai didi

javascript - Jest Mock - 将值插入测试文件

转载 作者:行者123 更新时间:2023-11-28 21:24:08 26 4
gpt4 key购买 nike

我在向被测文件中插入值时遇到问题:

import device from '../device'

let execute = () => {
if (device.isAndroid()) {
return true
else {
return false
}
}

现在是测试文件:

jest.mock('../device')
import device from '../device'

describe('when the device is Android', () => {
let device

beforeEach(() => {
device = jest.fn().mockImplementation(() => {
return {
isAndroid: () => { return true }
}
})
})

it('returns true', () => {
let results = execute()
expect(result).toEqual(true)
})
})

测试失败并返回false。我做错了什么?

最佳答案

你需要用一个 Jest spy 和模拟实现来模拟 '../device':

jest.mock('../device', ()=>{return {isAndroid: jest.fn()}})
import device from '../device'

describe('when the device is Android', () => {

beforeEach(() => {
device.isAndroid.mockImplementation(() => true)
})

it('returns true', () => {
let results = execute()
expect(result).toEqual(true)
})
})

关于javascript - Jest Mock - 将值插入测试文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44956345/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com