Search code examples
unit-testingjestjsnestjsnsubstitute

Use multiple return values in Substitute from '@fluffy-spoon/substitute'


I am using jest for unit testing of my nestJs service , for mocking a service from B to a service in A , i use Substitue module, but once a value (firstContractDocument) is set in return of mocked function of B , the same value is appearing in all 'it' tests. I tried of using arguments instead of 'Arg.any()' , nut it returns 'Proxy 'SubstituteJS'} jest'. Can anyone help me to return new value (secondContractDocument) in next 'it' instead of reappearing of previous value.

import Substitute, { Arg } from '@fluffy-spoon/substitute';
....
describe('Test CollaboratorService', () => {
const contractDocumentService = Substitute.for<ContractDocumentService>();
....
 beforeEach(async () => {
    const moduleRef = await Test.createTestingModule({
      imports: [],
      controllers: [],
      providers: [
        ....
        {
          provide: 'ContractDocumentService',
          useValue: contractDocumentService,
        },

      ],
     }).compile();
   ....
    });

it('should return collaborators with the given contractDocumentId', async () => {
      contractDocumentService
         .findOneOrFail(Arg.any())
        .returns(Promise.resolve(firstContractDocument));
});
it('should return collaborators with the given contractDocumentId', async () => {
      contractDocumentService
         .findOneOrFail(Arg.any())
        .returns(Promise.resolve(secondContractDocument));
});
....

return value is always 'firstContractDocument'

Need to change value on next 'it' test case to secondContractDocument


Solution

  • The problem is Arg.any() gives the fuction to return the constant whatever the argument is. So will return the first value whatever the argument is given. So specifically mention the argument instead of Arg.any(). The argment must be accurate in code and in logically, else there will be proxy error in return