【问题标题】:mocking API module is not resolved with mocked data模拟 API 模块无法通过模拟数据解析
【发布时间】:2017-11-28 11:58:07
【问题描述】:

我在模拟 async/await 函数时遇到了一个奇怪的问题。好吧,我有一个简单的 api.js 文件,它使用 fetch 调用来获取一些数据。我试图模拟这个电话,但到目前为止没有运气

api.js

export async function getUsers() {
    const resp = await fetch(`/users`);
    const data = await resp.json();
    return data.message;
}

__mock__/api.js

const users = [
    "Jhon",
    "Paul",
    "Ringo"
];

export default function getUsers() {
    return new Promise((resolve, reject) => {
        process.nextTick(() => {
            resolve(users)
        });
    });
}

api.test.js

jest.mock('./api');
import {getUsers} from "./api";

test("user list is an array", async () => {
    expect.assertions(1);
    const resp = await getUsers();
    expect(Array.isArray(resp)).toBe(true);
});

但我不断收到未定义的响应。

【问题讨论】:

  • 你解决了吗?我有类似的问题
  • 不应该是export function getUsers() 而不是export default function getUsers() 在你的__mock__/api.js 吗??

标签: jestjs


【解决方案1】:

您需要将export 更改为export defaultapi.js

api.js:

export default async function getUsers() {
  const resp = await fetch(`/users`);
  const data = await resp.json();
  return data.message;
}

__mocks__/api.js:

const users = ['Jhon', 'Paul', 'Ringo'];

export default function getUsers() {
  return new Promise((resolve, reject) => {
    process.nextTick(() => {
      resolve(users);
    });
  });
}

单元测试:

api.test.js:

import getUsers from './api';

jest.mock('./api');

test('user list is an array', async () => {
  expect.assertions(1);
  const resp = await getUsers();
  expect(Array.isArray(resp)).toBeTruthy();
});

单元测试结果:

 PASS  src/stackoverflow/47531051/api.test.ts
  ✓ user list is an array (8ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.852s

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多