I'm writing some tests for my component but I'm facing some troubles here...
Here is my Game component:
import React, { Component } from 'react';
import User from './user';
import Board from './board';
class Game extends Component {
constructor(props) {
super(props);
this.board = new Board();
//some more code
}
//some more code
initializeUser(name) {
const user = new User(name);
//some more code
user.pickCards();
//some more code
}
//some more code
render() {
return (
<div className="game-container">
</div>
);
}
}
export default Game;
My Board component:
import React, { Component } from 'react';
class Board extends Component {
constructor(props) {
super(props);
//some more code
}
//some more code
}
export default Board;
My User component:
import React, { Component } from 'react';
class User extends Component {
constructor(props) {
super(props);
this.name = this.props.name;
//some more code
}
//some more code
pickCards() {
//some code
}
//some more code
}
export default User;
Now, at my tests I'm trying to test if the Board
and User
are called and if the pickCards()
is called too.
Here are my tests:
import React from 'react';
import { mount } from 'enzyme';
import Game from './user';
import User from './user';
import Board from './board';
describe('Game start', () => {
//some more code
it('test 1', () => {
//some code
});
it('test where I having problems', () => {
const boardSpy = jest.spyOn(Board, 'constructor'),
userSpy = jest.spyOn(User, 'constructor'),
pickCardMock = jest.fn();
User.pickCard = pickCardMock;
const wrapper = mount(<Game />, { attachTo: container });
expect(boardSpy).toHaveBeenCalledTimes(1);
expect(userSpy).toHaveBeenCalledTimes(1);
expect(pickCardMock).toHaveBeenCalledTimes(1);
});
it('test 3', () => {
//some code
});
});
I don't want to mock Board
and User
because I need everything work normally on it. But I want to spy them to check if they were really called. And I want to mock pickCard()
.
I already tried to use jest.mock('./board');
and require('board')
(for example) inside my test but it didn't work. And now I'm trying to spy the components constructors.
But the expect(boardSpy).toHaveBeenCalledTimes(1)
fails saying that was called 0 times and not 1 time.
And the pickCardMock
seems not being linked to the User
module because when debugging pickCard
is a normal function and not a mock function and expect(pickCardMock).toHaveBeenCalledTimes(1)
receives 0 too instead of 1.
Anyone knows how to solve these two problems (spy a module and mock a function in the module)?
Aucun commentaire:
Enregistrer un commentaire