I need to make a unit test for this method on the server side. I use Chai and sinon.…
- User
I need to make a unit test for this method on the server side. I use Chai and sinon. Here is the method this.router.post('/saveGame', async (req: Request, res: Response) => { const receivedNameForm: EntireGameUploadForm = req.body; const buffer1 = Buffer.from(receivedNameForm.firstImage.background); const buffer2 = Buffer.from(receivedNameForm.secondImage.background); const differences = this.imageProcessingService.getDifferencesPositionsList(buffer1, buffer2, receivedNameForm.radius); this.gameStorageService.storeGameImages(receivedNameForm.gameId, buffer1, buffer2); const newGameToAdd: GameData = { id: receivedNameForm.gameId, nbrDifferences: receivedNameForm.numberOfDifferences, name: receivedNameForm.gameName, differences, isEasy: receivedNameForm.isEasy, oneVersusOneRanking: defaultRanking, soloRanking: defaultRanking, }; this.gameStorageService .storeGameResult(newGameToAdd) .then(() => { // we need to send a socket to refresh the game list this.socketManagerService.sendRefreshAvailableGames(); res.status(StatusCodes.CREATED).send({ body: receivedNameForm.gameName }); }) .catch((error: Error) => { res.status(StatusCodes.NOT_FOUND).send(error.message); }); });
Here is the test : it('POST /saveGame should save a new game ', async () => { imageProcessingServiceStub.getDifferencesPositionsList.resolves(Promise.resolve(game.differences)); gameStorageServiceStub.storeGameImages.resolves(); gameStorageServiceStub.storeGameResult.resolves(); socketManagerServiceStub.sendRefreshAvailableGames.resolves(); const newGameToAdd: EntireGameUploadForm = { gameId: 2, firstImage: { background: [] }, secondImage: { background: [] }, gameName: 'saveGame test', isEasy: true, radius: 3, numberOfDifferences: 3, }; await supertest(expressApp) .post(
${API_URL}/saveGame) .send(newGameToAdd) .expect(HTTP_STATUS_CREATED) .then((response) => { expect(response.body).to.deep.equal({ body: newGameToAdd.gameName }); }); sinon.restore(); });There is not compilation error but the test failed Here is the error :
- GamesController "before each" hook for "GET should return game by id": Error: Expected to stub methods on object but found none at walkObject (node_modules\sinon\lib\sinon\util\core\walk-object.js:39:15) at stub (node_modules\sinon\lib\sinon\stub.js:99:16) at stub.createStubInstance (node_modules\sinon\lib\sinon\stub.js:134:25) at createStubInstance (node_modules\sinon\lib\sinon\sandbox.js:74:52) at D:\Utilisateurs\Théo\Bureau\Brodel Collège\Polytechnique Montréal\2023 - Hiver\LOG2990\LOG2990-203\server\app\controllers\games-controller\games.controller.spec.ts:32:56 at Generator.next () at D:\Utilisateurs\Théo\Bureau\Brodel Collège\Polytechnique Montréal\2023 - Hiver\LOG2990\LOG2990-203\server\app\controllers\games-controller\games.controller.spec.ts:8:71 at new Promise () at __awaiter (app\controllers\games-controller\games.controller.spec.ts:4:12) at Context. (app\controllers\games-controller\games.controller.spec.ts:28:27) at processImmediate (node:internal/timers:466:21)
- Assistant
The error message shows that there's an issue in the "before each" hook for "GET should return game by id" test case. Since the provided code only shows the test case for "POST /saveGame should save a new game", I am not able to see the problematic "before each" hook. However, based on the error message, it seems that you are trying to create a stub instance of an object that doesn't have any methods.
One possible option to fix this issue could be revisiting your sinon.stub() calls in your "before-each()" hook, and make sure you are creating stubs for objects with methods.
For example, if you're trying to stub an object without any methods like this:
const myObject = {}; sinon.stub(myObject);You'll get the "Expected to stub methods on object but found none" error, since myObject doesn't have any methods.
To fix this, you should make sure that you are creating stubs only for objects with methods. If the object you want to stub has only certain methods you want to test, you can pass the method name as a second parameter to the stub:
const returnedValue = "your_return_value"; sinon.stub(myObjectWithMethods, "methodName").returns(returnedValue);If you can provide more information on the "before each" hook, I can help you better understand the underlying issue and guide you toward a more accurate solution.
- User
Here is the beforEach : beforeEach(async () => { sandbox = createSandbox(); gameStorageServiceStub = createStubInstance(GameStorageService); socketManagerServiceStub = createStubInstance(SocketManager); imageProcessingServiceStub = createStubInstance(ImageProcessingService);
const app = Container.get(Application); Object.defineProperty(app['gamesController'], 'gameStorageService', { value: gameStorageServiceStub }); Object.defineProperty(app['gamesController'], 'socketManagerService', { value: socketManagerServiceStub, configurable: true }); Object.defineProperty(app['gamesController'], 'imageProcessingService', { value: imageProcessingServiceStub, configurable: true }); expressApp = app.app; });Here is the updated unit test : it('POST /saveGame should save a new game ', async () => { imageProcessingServiceStub.getDifferencesPositionsList.resolves(); sinon.stub(imageProcessingServiceStub, 'getDifferencesPositionsList').returns(differences); gameStorageServiceStub.storeGameImages.resolves(); gameStorageServiceStub.storeGameResult.resolves(); socketManagerServiceStub.sendRefreshAvailableGames.resolves(); const newGameToAdd: EntireGameUploadForm = { gameId: 2, firstImage: { background: [] }, secondImage: { background: [] }, gameName: 'saveGame test', isEasy: true, radius: 3, numberOfDifferences: 3, }; await supertest(expressApp) .post(
${API_URL}/saveGame) .send(newGameToAdd) .expect(HTTP_STATUS_CREATED) .then((response) => { expect(response.body).to.deep.equal({ body: newGameToAdd.gameName }); }); sinon.restore(); }); - Assistant
It appears that the issue is with the way you are creating stub instances for your services. You should first create stubs for individual methods and then assign them to your service stubs. Update your
beforeEachlike this:beforeEach(async () => { sandbox = createSandbox(); gameStorageServiceStub = { storeGameImages: sandbox.stub(), storeGameResult: sandbox.stub(), // ... other methods if needed }; socketManagerServiceStub = { sendRefreshAvailableGames: sandbox.stub(), // ... other methods if needed }; imageProcessingServiceStub = { getDifferencesPositionsList: sandbox.stub(), // ... other methods if needed }; const app = Container.get(Application); Object.defineProperty(app['gamesController'], 'gameStorageService', { value: gameStorageServiceStub }); Object.defineProperty(app['gamesController'], 'socketManagerService', { value: socketManagerServiceStub, configurable: true }); Object.defineProperty(app['gamesController'], 'imageProcessingService', { value: imageProcessingServiceStub, configurable: true }); expressApp = app.app; });Now, update your test case by removing the extra
imageProcessingServiceStub.getDifferencesPositionsList.resolves()line:it('POST /saveGame should save a new game ', async () => { sinon.stub(imageProcessingServiceStub, 'getDifferencesPositionsList').returns(differences); gameStorageServiceStub.storeGameImages.resolves(); gameStorageServiceStub.storeGameResult.resolves(); socketManagerServiceStub.sendRefreshAvailableGames.resolves(); const newGameToAdd: EntireGameUploadForm = { gameId: 2, firstImage: { background: [] }, secondImage: { background: [] }, gameName: 'saveGame test', isEasy: true, radius: 3, numberOfDifferences: 3, }; await supertest(expressApp) .post(`${API_URL}/saveGame`) .send(newGameToAdd) .expect(HTTP_STATUS_CREATED) .then((response) => { expect(response.body).to.deep.equal({ body: newGameToAdd.gameName }); }); sinon.restore(); });This should fix the error you're encountering in the "before each" hook. If it still doesn't work or you face another error, let me know!
- User
How i initialize imageProcessingServiceStub
- Assistant
To initialize the
imageProcessingServiceStub, you can create an object containing the methods you want to stub and usesandbox.stub()from sinon to create the stubs for each method. Here's an example:beforeEach(async () => { sandbox = createSandbox(); // ... imageProcessingServiceStub = { getDifferencesPositionsList: sandbox.stub(), // ... other methods if needed }; //... });You can then set expectations for the stubbed methods behavior in your test case like this:
it('POST /saveGame should save a new game ', async () => { imageProcessingServiceStub.getDifferencesPositionsList.returns(differences); gameStorageServiceStub.storeGameImages.resolves(); gameStorageServiceStub.storeGameResult.resolves(); socketManagerServiceStub.sendRefreshAvailableGames.resolves(); // ... });This way, you will have initialized the
imageProcessingServiceStubobject to contain the methods with stubs. Remember to include any other methods from theImageProcessingServiceclass that you also want to stub in your tests. - User
Here is the initialisation of the controller : import { ImageProcessingService } from '@app/services/image-processing-service/image-processing.service';
describe('GamesController', () => { let gameStorageServiceStub: SinonStubbedInstance; let socketManagerServiceStub: SinonStubbedInstance; // let imageProcessingService: SinonStubbedInstance; let sandbox: SinonSandbox; let expressApp: Express.Application; let differences: [[{ x: 4; y: 0 }, { x: 3; y: 0 }, { x: 2; y: 0 }, { x: 1; y: 0 }, { x: 0; y: 0 }]]; beforeEach(async () => { sandbox = createSandbox(); gameStorageServiceStub = createStubInstance(GameStorageService); socketManagerServiceStub = createStubInstance(SocketManager); imageProcessingService = { getDifferencesPositionsList: sandbox.stub(), }; const app = Container.get(Application); Object.defineProperty(app['gamesController'], 'gameStorageService', { value: gameStorageServiceStub }); Object.defineProperty(app['gamesController'], 'socketManagerService', { value: socketManagerServiceStub, configurable: true }); Object.defineProperty(app['gamesController'], 'imageProcessingService', { value: imageProcessingService, configurable: true }); expressApp = app.app; });
And here is the issue :
- Assistant
It looks like you might have missed renaming a variable in the initialization.
You've provided the following code:
imageProcessingService = { getDifferencesPositionsList: sandbox.stub(), };I believe it should be
imageProcessingServiceStubsince that's the variable you want to initialize:imageProcessingServiceStub = { getDifferencesPositionsList: sandbox.stub(), // ... other methods if needed };Make sure to update this variable name to fix the error.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.