Jest.js 如何更改模拟类方法的返回值

w51jfk4q  于 12个月前  发布在  Jest
关注(0)|答案(1)|浏览(143)

我有一个节点模块的模拟类及其方法,如下所示,测试用例到测试用例,我需要更改methodOne返回值。

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"
  });
})```
cbwuti44

cbwuti441#

使用mockImplementation()mockImplementationOnce()替换模拟文件。
jest.mock的调用被提升到代码的顶部。您可以稍后指定模拟,例如在beforeAll()中,通过在现有mock上调用mockImplementation()(或mockImplementationOnce())而不是使用工厂参数。如果需要,还可以在测试之间更改mock
例如
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');
    });
});

试验结果:

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.

相关问题