简体   繁体   中英

how to mock variable inside function typeorm nestjs

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 show up

Can't createBoth [ because I think It need to mock data.id ] 

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM