Reputation: 805
I'm trying to mock an ES6 class constructor using jest v23.6.0 and babel 6.22.1. The actual code is more complicated, obviously, than what's below, but I've stripped it down to just this and still have the issue.
I have the following class:
StageComponent.js
export default class StageComponent {
constructor () {}
}
and the following test code:
import StageComponent from './StageComponent';
jest.mock('./StageComponent');
describe('StageComponent', () => {
it('should track constructor', () => {
let c = new StageComponent();
expect(StageComponent).toHaveBeenCalled();
});
});
When I test this, I get
jest.fn() value must be a mock function or spy.
Received:
function: [Function StageComponent]
6 | let c = new StageComponent();
7 |
> 8 | expect(StageComponent).toHaveBeenCalled();
| ^
9 | });
10 | });
11 |
No matter what I try, it's like the mock() call isn't doing anything. Jest otherwise seems to be working fine (e.g. I have replaced individual properties with jest.fn() successfully) so I don't think it's my installation. Is there something I'm missing? This seems to be straight out of the docs...
EDIT: The actual code for the test was:
import StageComponent from '@/StageComponent';
jest.mock('@/StageComponent');
...
and my changing it for simplicity when I posted this obscured the issue, which was the webpack alias @
in the path. It works fine if I give it the full path (including the .js at the end) in both the import
and the mock()
. So now the question is why the alias doesn't work. (Also note that using the alias in the import
and not in the mock()
produces the same outcome, if that's a clue).
In webpack config I have this alias
:
'@': resolve('src')
In jest config I have this moduleNameMapper
:
'^@/(.*)$': '<rootDir>/src/$1'
And in fact if I change the moduleNameMapper
it throws errors about not finding the file, so I would think if it weren't working at all, it would be throwing similar errors rather than not applying the mock()
Upvotes: 1
Views: 1119
Reputation: 805
When running on Windows, the capitalization has to match across all of the import
statements throughout the code (across all files) and the mock()
statements. You'll obviously get an error on other platforms if that's the not case, but on Windows it will successfully load the file with no errors, but the import
and the mock
won't line up and thus the mocked constructor doesn't get called.
Upvotes: 1