【问题标题】:Jest Mock - inserting values into tested fileJest Mock - 将值插入测试文件
【发布时间】:2017-07-07 16:40:24
【问题描述】:

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

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。我做错了什么?

【问题讨论】:

    标签: javascript unit-testing testing jestjs


    【解决方案1】:

    你需要用一个玩笑的间谍来模拟'../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)
      })
    })
    

    【讨论】:

    • 感谢您的回答,但我收到以下错误:TypeError: device.isAndroid is not a function - at execute (src/execute.js). TypeError: Cannot read property 'mockImplementation' of undefined - at Object.<anonymous> (src/test/execute.spec.js) 有什么想法吗?
    • 不确定,更新了我的答案以将模拟直接移动到isAndroid
    • 首先,你是个天才!!我让它工作。请更新上述答案,我会将其标记为正确(只是想确保其他人不会误入歧途)。第一行应该是jest.mock('../device', ()=>{return {isAndroid: jest.fn()}}) 另外,删除let device 因为设备已经由import 语句定义。这使它起作用。
    猜你喜欢
    • 2017-07-15
    • 1970-01-01
    • 2018-09-16
    • 2021-09-05
    • 2018-07-28
    • 2020-12-04
    • 2020-05-25
    • 2020-06-02
    • 1970-01-01
    相关资源
    最近更新 更多