Home > Back-end >  How to mock and set function argument correctly in jest mock
How to mock and set function argument correctly in jest mock

Time:09-10

I would like to test my mocking by following jest script.I intended to mock exec in returnvalueirohaResponse but , when I run following test,IrohaTransactionExec().exec("testArg1","testArg2") was executed and not returned irohaResponse

What is the wrong point of that? and How can I mock correctly? Thanks

        it("mocking test",async ()=>{
            const irohaResponse= registered;
            const iroha = new IrohaTransactionExec()
            const mockfunc = jest.spyOn(iroha,"exec")
            mockfunc.mockReturnValue(Promise.resolve(irohaResponse))
            expect(await new IrohaTransactionExec().exec("testArg1","testArg2")).toEqual(irohaResponse)
        },10000)
import { IrohaClientBuilder,IrohaRequestParam } from "@post-pricing/library/lib/src/utility"
import { IrohaInterface } from "@post-pricing/library/lib/src/const/irohaApi"

export class IrohaTransactionExec {

    private irohaClient:IrohaClientBuilder
    private irohaRequestParam:IrohaRequestParam

    constructor(){
        this.irohaRequestParam = new IrohaRequestParam()
    }

    public async exec (shopCode:string,nptransactionId:string):Promise<IrohaInterface> {
        this.irohaClient = new IrohaClientBuilder()
        const client = await this.irohaClient.buildIrohaClient()
        const result = await client.searchTransactionAsync(this.irohaRequestParam.get(shopCode,nptransactionId))
        return result[0].return
    } 

}
 expect(received).toEqual(expected) // deep equality

    - Expected  - 37
      Received     6

      Object {
        "apiCommonResponseHeader": Object {
          "attributes": Object {
            "xsi:type": "ax22:ApiCommonResponseHeader",
          },
    -     "requestId": "12345",
    -     "resultStatus": 0,
          "errorCodeList": Array [
            "E0000007",
          ],
          "requestId": "PRC220909141357mwdix",
          "resultStatus": 90,
          "serviceType": "01",
    -     "shopCode": "akt0000001",
          "shopCode": "testArg1"}
}
      20 |             const mockfunc = jest.spyOn(iroha,"exec")
      21 |             mockfunc.mockReturnValue(Promise.resolve(irohaResponse))
    > 22 |             expect(await new IrohaTransactionExec().exec("testArg1","testArg2")).toEqual(irohaResponse)
         |                                                                                  ^
      23 |         },10000)
     

      at Object.<anonymous> (test/functions/transactions/handler.spec.ts:22:82)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |       0 |        0 |       0 |       0 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        3.754 s, estimated 4 s

CodePudding user response:

I guess the issue is that in your expectation you are creating a new instance, and therefor it's not mocked anymore.

Following the docs, I would possible do the following:

import IrohaTransactionExec from './path-to-module';

const mockExec = jest.fn();

jest.mock('./path-to-module', () => {
  return jest.fn().mockImplementation(() => {
    return { exec: mockExec };
  });
});
// OR
jest.mock('./path-to-module', () => ({
  exec: mockExec
}));

// describe...
beforeEach(() => {
  mockExec.mockResolvedValue(registered);
});

it("mocking test", async () => {
  const res = await new IrohaTransactionExec().exec("testArg1","testArg2");
  expect(res).toEqual(irohaResponse)
)}
  • Related