jestjs - 手动模拟未被拾取

标签 jestjs

Jest 不提供我的手动模拟。一切似乎都在正确的目录中。我错过了什么?

src/adapters/__mocks__/Foo.js

const spy = jest.genMockFromModule('../Foo')

function doStuff() {
  return { source: 'mock' }
}

spy.doStuff = doStuff
module.exports = spy

src/adapters/Foo.js

class Foo {
  doStuff() {
    return { source: 'real' }
  }
}

module.exports = Foo

src/adapters/__tests__/Foo.js

const Foo = require('../Foo')

test('Foo', () => {
  const foo = new Foo()
  expect(foo.doStuff()).toEqual({ source: 'mock' })
})

测试输出:

expect(received).toEqual(expected)

    Expected value to equal:
      {"source": "mock"}
    Received:
      {"source": "real"}

    Difference:

    - Expected
    + Received

      Object {
    -   "source": "mock",
    +   "source": "real",
      }

      3 | test('Foo', () => {
      4 |   const foo = new Foo()
    > 5 |   expect(foo.doStuff()).toEqual({ source: 'mock' })
      6 | })
      7 |

      at Object.<anonymous>.test (adapters/__tests__/Foo.js:5:25)

Jest 版本:“jest-cli”:“^23.0.0-alpha.0”

从长远来看,尝试了这个,但没有奏效。没有找到模拟,只是给了我 undefined 正如我在调用 doStuff() 时所期望的那样

src/adapters/__tests__/Foo.js

//TREID this but didn't work
jest.mock('../Foo')

const Foo = require('../Foo')

test('Foo', () => {
  const foo = new Foo()
  expect(foo.doStuff()).toEqual({ source: 'mock' })
})

最佳答案

试试下面的代码,这里的问题是我们模拟 ES6 类的方式,基本上,有 4 种方法可以模拟 class,如文档中所述

https://facebook.github.io/jest/docs/en/es6-class-mocks.html

src/adapters/__mocks__/Foo.js

const mock = jest.fn().mockImplementation(()=>{
   return {
       doStuff: jest.fn(()=>({source: 'mock'}))
   } 
});

module.exports = mock;

src/adapters/__tests__/Foo.js

jest.mock('../Foo');

const Foo = require('../Foo');

test('Foo', () => {
    const foo = new Foo();
    expect(foo.doStuff()).toEqual({ source: 'mock' })
});

(或)

内联模拟也可以工作

src/adapters/__tests__/Foo.js

jest.mock('../Foo', () => {
    return jest.fn().mockImplementation(() => {
        return {
            doStuff: jest.fn(() => ({ source: 'mock' }))
        }
    });
});


const Foo = require('../Foo');

test('Foo', () => {
    const foo = new Foo();
    expect(foo.doStuff()).toEqual({ source: 'mock' })
});

关于jestjs - 手动模拟未被拾取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49482257/

相关文章:

javascript - 如何在模拟的 Jest 函数中使用 var 作为返回值?

javascript - 为什么我的异步 Jest 测试没有在应该失败的时候失败?

typescript - 我应该把 index.d.ts 文件放在哪里?

react-native - 开 Jest : Test suite failed to run, TypeError:无法读取未定义的属性 'bind'

javascript - Formik 测试错误 : The `document` global was defined when React was initialized, 但不再定义

javascript - 模拟来自同一个类的 promise 返回方法

reactjs - 无效的 Chai 属性 : toMatchSnapshot -- React. js Jest 测试

javascript - 如何监视对于Jest方式导入的函数

javascript - 如何使用 Jest 模拟构造函数状态初始化

angular - 模拟类以使用 Typescript 和 Jest 进行测试