jazimabbas / mock-typeorm

MockTypeORM - Never hit the database again while testing.
https://mock-typeorm-docs.vercel.app
MIT License
1 stars 1 forks source link

Multiple Function Mocks Issue #1

Closed sloughrey closed 1 month ago

sloughrey commented 1 month ago

Hi there,

First off, thanks for creating this package, it has helped get started with a mocked TypeORM quite quickly!

I am currently running into an issue where when trying to mock return data using onMock for 2 different functions, findOneBy and insert, the findOneBy mock data is being deleted all together and only the insert mock data remains. To reproduce this the code would look as follows:

const typeormMock = new MockTypeORM();
typeormMock
.onMock("Test")
.toReturn("test1", "findOneBy")
.toReturn("test2", "findOneBy")
.toReturn("testInsert", "insert")

At the end of that script, only the insert mock data remains in my codebase.

I was digging into the source code and I did notice something a bit strange, I'm not sure if it is intentional or not. In the toReturn function it looks like it overwrites all previous data in the repository if the mockMethod value is undefined.

 toReturn(mockData: any, method = "find") {
        if (!self.mocks[repositoryName]) {
          self.mocks[repositoryName] = {};
        }

        const mockMethod = self.mocks[repositoryName][method];
        if (mockMethod) {
          const totalMockItemsFoundInMethod = Object.keys(mockMethod).length;
          mockMethod[totalMockItemsFoundInMethod] = mockData;
        } else {
         // ********** THIS IS OVERWRITING PREVIOUS DATA ***********
          self.mocks[repositoryName] = { [method]: { 0: mockData } };

          // initialize mock history with empty state
          if (!self.mockHistory[repositoryName]) {
            self.mockHistory = { ...self.mockHistory, [repositoryName]: {} };
          }
          self.mockHistory[repositoryName] = { [method]: 0 };
        }

        return this;
      },

Instead of that line below the comment "** THIS IS OVERWRITING PREVIOUS DATA ***" should it not read as follows: self.mocks[repositoryName][method] = { 0: mockData };

This way, all previously mocked function data for other function names remain since the repository data is not completely overwritten when a new mocked function name is provided.

Any help would be greatly appreciated!

jazimabbas commented 1 month ago

@sloughrey published a new npm version . I am closing this PR. If you still face any issue. Feel free to open a new PR. Thanks.