如何在玩笑中模拟 const 方法?

Quo*_* Vo 7 javascript typescript jestjs

我在打字稿中单元测试代码,使用开玩笑。请教我如何模拟getData以返回预期值。我的代码如下:

// File util.ts
export const getData = async () => {
    // Todo something
    return data;
}

// File execution.ts import { getData } from './util';
function execute()
{
    // todo something
    const data = await getData();
    // todo something 
}
Run Code Online (Sandbox Code Playgroud)

And*_*rle 6

问题是你的函数返回一个承诺。取决于您如何使用它,有多种方法可以模拟它。

最简单的方法是直接模拟它,但它总是会返回相同的值:

// note, the path is relative to your test file
jest.mock('./util', () => ({ getData: () => 'someValue' }));
Run Code Online (Sandbox Code Playgroud)

如果您想测试已解决和已拒绝的情况,您需要模拟,getData以便它返回一个间谍,您以后可以在其中更改实现 use mockImplementation。您还需要使用async/await来使测试工作,请查看有关异步测试的文档

import { getData } from './util';
jest.mock('./util', () => ({ getData: ()=> jest.fn() }));

it('success case', async () => {
  const result = Promise.resolve('someValue');
  getData.mockImplementation(() => result);

  // call your function to test
  await result; // you need to use await to make jest aware of the promise
});

it('error case', async () => {
  const result = Promise.reject(new Error('someError'));
  getData.mockImplementation(() => result);

  // call your function to test
  await expect(result).rejects.toThrow('someError');
});
Run Code Online (Sandbox Code Playgroud)


anu*_*b26 1

在您的测试文件中尝试以下操作。从模块导入函数。

 import { getData } from './util';
Run Code Online (Sandbox Code Playgroud)

然后在所有 import 语句之后使用函数及其返回值模拟模块

jest.mock('./util', () => ({ getData: jest.fn() }))
getData.mockReturnValue("abc");
Run Code Online (Sandbox Code Playgroud)

然后在您的测试中使用它。