English 中文(简体)
How to change return value of mocked class method
原标题:

I have a mocked class of a node module and its method as below, and test case to test case I need to change the methodOne returning value.

jest.mock("module_name", () => {
  return {
    __esModule: true,
    Abc: class Abc {
      constructor(config) {}

      async methodOne(params) {
        return {
          message: {
            content:
               This text I need to change ,
          },
        };
      }
    },
    Configuration: class Configuration {
      constructor(config) {
        return true;
      }
    },
  };
});

describe("getVeganStatus", () => {
  it("should handle case one......", async () => {
    // methodOne message.content return value should be "ABC"
  })

  it("should handle case two......", async () => {
    // methodOne message.content return value should be "XYZ"
  });
})```
问题回答

Following Replacing the mock using mockImplementation() or mockImplementationOnce() documentation.

Calls to jest.mock are hoisted to the top of the code. You can specify a mock later, e.g. in beforeAll(), by calling mockImplementation() (or mockImplementationOnce()) on the existing mock instead of using the factory parameter. This also allows you to change the mock between tests, if needed:

E.g.

some-module.js:

export class Abc {
  constructor(config) {}

  async methodOne(params) {
    return {
      message: {
        content:
           This text I need to change ,
      },
    };
  }
}

main.js:

import { Abc } from  ./some-module ;

export async function main() {
    const abc = new Abc();
    return abc.methodOne().then((res) => res.message.content);
}

main.test.js:

import { main } from  ./main ;
import { Abc } from  ./some-module ;

jest.mock( ./some-module );

describe( 76863882 , () => {
    test( should pass 1 , async () => {
        Abc.mockImplementation(() => {
            return {
                methodOne: async () => ({ message: { content:  ABC  } }),
            };
        });
        const actual = await main();
        expect(actual).toBe( ABC );
    });

    test( should pass 2 , async () => {
        Abc.mockImplementation(() => {
            return {
                methodOne: async () => ({ message: { content:  XYZ  } }),
            };
        });
        const actual = await main();
        expect(actual).toBe( XYZ );
    });
});

Test result:

 PASS  stackoverflow/76863882/main.test.js (5.787 s)
  76863882
    ✓ should pass 1 (2 ms)
    ✓ should pass 2

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        5.978 s, estimated 6 s
Ran all test suites related to changed files.




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签