簡體   English   中英

ValidateUsername 是只讀的 | 帶有笑話/酶的 TS

[英]ValidateUsername is read-only | TS with Jest/Enzyme

我有一個小的實用函數,我正在我的 React-TS 項目上用 Jest 和 Enzyme 進行一些測試。 在該項目的 JS 文件中,我收到以下錯誤:

"validateUsername" is read-only.

這是實用程序本身:

export const validateUsername = value =>
  listUsers()
    .then(({ data }) => {
      if (Array.isArray(data) && data.find(userData => userData.username === value)) {
        throw 'Username already exists';
      }
    })
    .catch(error => {
      throw serverErrorResponseUtil(error);
    });

這是對它的測試:

describe('Validate Username', () => {
  const validateUsernameFn = jest.fn();
  beforeEach(() => {
    validateUsername = validateUsernameFn;
  });

  it('Should throw an error if the given value exists', async () => {
    try {
      await validateUsername('username');
    } catch (e) {
      expect(e).toEqual('Username already exists');
    }
  });

  it('Accept the data if the passed userName is unique', async () => {
    expect(() => validateUsername('Username is unique')).not.toThrow();
  });
});

我在這里收到錯誤: validateUsername = validateUsernameFn; . 問題是這個文件是一個js文件。 為什么我收到關於只讀的 ts 錯誤。 你們能幫我嗎?

您可能已經找到了解決方案,但問題是您導入了validateUsername ,然后在beforeEach()重新定義了它。

我不知道為什么你需要beforeEach()的代碼,但如果你想訪問初始validateUsername + 享受jest.spyOn的好處,我建議使用jest.spyOn

如果需要,在beforeEach()您可以清除測試之間的beforeEach()

看起來你要將你的函數export const validateUsernameexport const validateUsername ,然后嘗試在拋出錯誤的行上重新分配它。 constant s不能重新分配(按設計),只letvar可以。

它並不完全清楚,但看起來你不需要在這里使用jest.fn - 這是用於創建模擬'間諜'函數,所以你可以檢查一個函數是否使用正確的參數調用。 您正在嘗試測試函數本身,因此無需將其重新分配給開玩笑的間諜。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM