I want to test function that do .save into 2 table but in 2nd query I have to use id from 1st query here is my service.
async createBoth(createInput: CreateInput): Promise<SomeThing> {
const data = await this.dataRepository.create(createInput);
const data2 = {
dataId: data.id,
someInfo: 'test'
};
await this.data2Repository.create2(wallet);
}
As you see in my function I have 2 queries first I save into dataReposition
, then I save into data2Repository by using data.id
.
Here is my test:
describe('create Boath', () => {
it('should be createBoth', async () => {
await service.createBoth(mockInput);
});
});
The error shows up:
Can't createBoth [ because I think It need to mock data.id ]
CodePudding user response:
I think, You are going a bit wrong about unit testing. Ofc, everybody has own preference on how to do it... but in any case.
Unit testing in its basic form is to test logic of one particular method, not the methods it is calling (in this respect, writing testable code is also important).
So, what you want to mock in your case are the 2 objects that are referenced as this.dataRepository and this.data2Repository. Those objects have to have that create() methods mocked.
This will allow you to control, what data is returned from first call and to verify what are the call parameters to both calls.
Your test should do the above verifications, otherwise it is not really testing much except if the call fails drastically.
Speaking of which, in your code you don't use data2 constant after its declaration. Are you sure it is the "wallet" variable that you need to pass to the 2nd call and not data2?