Nock和Jasmine单元测试-node js环境

问题描述 投票:0回答:0

刚接触nock,第一次用

我想测试以下方法,但我的测试失败了

Expected spy storeDeviceId to have been called with: [ '1234-5678' ]
但它从未被调用过。

我怀疑这是一个 nock 问题,测试中有更多用户错误,但我们将不胜感激

测试方法

async function getDeviceId() {
  const API_URL = `${BASE_URL}/endpoint_url`;

  try {
    const response = await fetch(API_URL);
    if (!response.ok) {
      throw new Error(`HTTP error ${response.status}`);
    }

    const uuid = await response.text();

    if (uuid) {
      await storeDeviceId(uuid);
    } else {
      throw new Error("UUID is not available");
    }
  } catch (error) {
    console.error("Error fetching uuid:", error);
  }
}

单元测试

import { exportedForTesting } from "../src/my_helper.js";
const { storeDeviceId, getDeviceId } = exportedForTesting;
import nock from 'nock';

describe("getDeviceId", () => {
  beforeEach(() => {
    nock.disableNetConnect();
  });

  afterEach(() => {
    nock.cleanAll();
    nock.enableNetConnect();
  });

  it("should call storeDeviceId with a valid UUID when the API call is successful", async () => {
    const mockUuid = '1234-5678';
    nock(BASE_URL)
      .get('/endpoint_url')
      .reply(200, mockUuid);
    
    const storeDeviceIdSpy = spyOn(exportedForTesting, 'storeDeviceId');
    await getDeviceId();

    expect(storeDeviceIdSpy).toHaveBeenCalledWith(mockUuid);
});

只是想知道是否有人有任何指示或让我知道我可能做错了什么?

谢谢

javascript jasmine nock
© www.soinside.com 2019 - 2024. All rights reserved.