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

时间:2019-02-15 05:50:06

标签: 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 
}

3 个答案:

答案 0 :(得分:1)

问题在于您的函数返回了一个Promise。取决于您如何使用它,有几种方法可以对其进行模拟。

最简单的方法是直接对其进行模拟,但随后它将始终返回相同的值:

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

如果要同时测试已解决和已拒绝的情况,则需要模拟getData,这样它将返回一个间谍,以后您可以在其中更改使用mockImplementation的实现。您还需要使用async/await来进行测试,看看docs关于异步测试:

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');
})

答案 1 :(得分:0)

在测试文件中尝试以下操作。  从模块导入功能。

import { Link} from '@myScope/myreactlib/Link'; // loaded from node_modules

然后在所有import语句之后用功能及其返回值模拟模块

 import { getData } from './util';

然后在测试中使用它。

答案 2 :(得分:0)

因为嘲笑表达式函数可能是使人痛苦的真正原因,所以我在下面发布了完整的示例。

场景

假设我们要测试一些执行REST调用的代码,但我们不希望进行实际的REST调用:

// doWithApi.ts

export const doSomethingWithRest = () => {
    post("some-url", 123);
}

post是单独文件中的函数表达式

// apiHelpers.ts

export const post = (url: string, num: number) => {
    throw Error("I'm a REST call that should not run during unit tests!");
}

设置

由于post函数是直接使用的(而不是作为参数传递的),因此我们必须创建一个 mock文件,Jest可以在测试期间使用它来代替真实的{ {1}}功能:

post

间谍和测试

现在,终于在实际测试中,我们可以执行以下操作:

// __mocks__/apiHelpers.ts

export const post = jest.fn();

示例使用Jest 24.9.0和Typescript 3.7.4

相关问题