AfterWorkGuinness
AfterWorkGuinness

Reputation: 1850

Manual mock not being picked up

Jest is not providing my manual mock. Everything appears to be in the correct directories. What am I missing?

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' })
})

Test Output:

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 Version: "jest-cli": "^23.0.0-alpha.0"

On a long shot, tried this, but didn't work. Didn't find the mock, just gave me undefined as I'd expect when calling 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' })
})

Upvotes: 3

Views: 3798

Answers (2)

Raja Jaganathan
Raja Jaganathan

Reputation: 36127

Try with below code, Problem here is the way we are mocking ES6 Classes, basically, there are 4 ways to mock the class as described in docs

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' })
});

(or)

Inline mocks also will works

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' })
});

Upvotes: 3

Brandon Tom
Brandon Tom

Reputation: 969

Have you tried adding the __mocks__ (or where ever your mocks live) directory to your roots in your package.json?

"jest": {
  "roots": [
    "<rootDir>/__mocks__",
    "<rootDir>/src"
  ],
...

Upvotes: 0

Related Questions