RequireActual用于手动模拟。

huangapple go评论72阅读模式
英文:

RequireActual for a manual mock

问题

在一个手动模拟文件__mocks__/axios.js中,我模拟了axios,但有时我想使用实际的axios实现(就像注释掉的那行代码所做的那样)。

在我的测试中,axios不会直接使用。因此,我尝试在测试套件中取消手动模拟:

test('200 response', async () => {
    jest.mock("axios", () => jest.requireActual("axios"))
    const response = await getContent('SomeID')
    expect(response.id).toEqual('SomeID');
})

但这似乎没有改变任何事情,测试失败,因为axios.get没有返回有用的内容。

是否有一种方式可以在测试中完全不使用手动模拟?

英文:

Searched everywhere, but couldn't find.

I'm mocking axios in a manual mock __mocks__/axios.js:

let mockAxios = jest.genMockFromModule('axios')
// mockAxios = jest.requireActual('axios')

export default mockAxios

But sometimes I want to use the actual axios implementation (like what the commented out line does).

In my test axios is not used directly. So I tried to undo manual mock for that test suite:

test('200 response', async () => {
    jest.mock("axios", () => jest.requireActual("axios"))
    const response = await getContent('SomeID')
    expect(response.id).toEqual('SomeID');
  })

This doesn't seem to change anything and the test fails because axios.get doesn't return anything useful.

Is there a way to have a test, or a test file where manual mock is not used at all?

答案1

得分: 1

I will translate the provided content:

我将翻译提供的内容:

I will use jest.dontMock(moduleName) to let specific test cases use the real module implementation.

我将使用 jest.dontMock(moduleName) 来让特定的测试用例使用真实的模块实现。

Don't forget to reset the module registry - the cache of all required modules. jest.resetModules() will do this.

不要忘记重置模块注册表 - 所有必需模块的缓存。 jest.resetModules() 将会做这个。

E.g.

例如:

__mocks__/axios.js:

let mockAxios = jest.genMockFromModule('axios')

mockAxios.get = jest.fn().mockResolvedValue({ data: 'fake' })

export default mockAxios

main.ts:

import axios from 'axios';

export function main() {
  return axios.get('https://jsonplaceholder.typicode.com/todos/1');
}

main.test.ts:

describe('76428962', () => {
  beforeEach(() => {
    jest.resetModules();
  })
  test('should mock axios', async () => {
    const { main } = await import('./main');
    const actual = await main();
    console.log(actual?.data);
  });
  test('should not mock axios', async () => {
    jest.dontMock('axios');
    const { main } = await import('./main');
    const actual = await main();
    console.log(actual?.data);
  });
});

测试结果:

  console.log
    fake

      at stackoverflow/76428962/main.test.ts:8:13

 PASS  stackoverflow/76428962/main.test.ts (15.823 s)
  76428962
    ✓ should mock axios (96 ms)
    ✓ should not mock axios (208 ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        16.28 s, estimated 19 s
Ran all test suites related to changed files.
  console.log
    { userId: 1, id: 1, title: 'delectus aut autem', completed: false }

      at stackoverflow/76428962/main.test.ts:14:13

Please let me know if you need any further assistance.

英文:

I will use jest.dontMock(moduleName) to let specific test cases use the real module implementation.

Don't forget to reset the module registry - the cache of all required modules. jest.resetModules() will do this.

E.g.

__mocks__/axios.js:

let mockAxios = jest.genMockFromModule('axios')

mockAxios.get = jest.fn().mockResolvedValue({ data: 'fake' })

export default mockAxios

main.ts:

import axios from 'axios';

export function main() {
  return axios.get('https://jsonplaceholder.typicode.com/todos/1');
}

main.test.ts:

describe('76428962', () => {
  beforeEach(() => {
    jest.resetModules();
  })
  test('should mock axios', async () => {
    const { main } = await import('./main');
    const actual = await main();
    console.log(actual?.data);
  });
  test('should not mock axios', async () => {
    jest.dontMock('axios');
    const { main } = await import('./main');
    const actual = await main();
    console.log(actual?.data);
  });
});

Test result:

  console.log
    fake

      at stackoverflow/76428962/main.test.ts:8:13

 PASS  stackoverflow/76428962/main.test.ts (15.823 s)
  76428962
    ✓ should mock axios (96 ms)
    ✓ should not mock axios (208 ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        16.28 s, estimated 19 s
Ran all test suites related to changed files.
  console.log
    { userId: 1, id: 1, title: 'delectus aut autem', completed: false }

      at stackoverflow/76428962/main.test.ts:14:13

huangapple
  • 本文由 发表于 2023年6月8日 13:56:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76428962.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定