1
0

More than 1 year has passed since last update.

Vue Jest Error: Not implemented: navigation の対策 [document.createElementの場合]

Last updated at Posted at 2022-11-10

問題

Error: Not implemented: navigation

jestで使用される jsdom はナビゲーションをサポートしていないため
window.location.href などを実行すると、このメッセージが表示される

エラーを起こすコード(例)

クリックでファイルをダウンロードするコード

component

download(fileId) {
  const url = `https://hogehoge.com/{fileId}`;
  const link = document.createElement('a');
  link.id = 'downloadFileLink';
  link.href = url;
  link.download = url;
  link.click();
}

jest

test('ダウンロード後完了メッセージが表示される', async () => {
  wrapper = mount(component, {
    store,
    vuetify,
    localVue,
  });

  // クリック
  wrapper.find(sel('downloadBtn')).trigger('click');

  // Promise処理待ち
  await flushPromises();

  // ダウンロード完了メッセージ確認
  expect(wrapper.find(sel('downloadText')).text()).toEqual('Downloaded');
});


解決方法

function makeAnchor(target) {
  return {
    target,
    setAttribute: jest.fn((key, value) => (target[key] = value)),
    click: jest.fn(() => {}),
    remove: jest.fn(() => {}),
  };
}
const anchor = makeAnchor({href: '#', download: ''});
const createElementMock = jest.spyOn(document, 'createElement').mockReturnValueOnce(anchor);

/**
 * - window.location.hrefを起こすアクション
 */

// 終わったらMockをrestore
createElementMock.mockRestore();

[回避したいこと]
createElement で作る aタグのイベント click で
window.location.href が実行されておきるエラー

[手順]

  1. clickのイベントをmockしたオブジェクトを作る
  2. [1] のオブジェクトでcreateElementのmockを作る
  3. createElementをspyOnしてmockしたものを渡す
  4. window.location.href は実行されない

余談

window.locationをmockする方法はたくさんあったが
直接 window.location をmockしても意味がなかった

document.createElementで作成したもの自体をmockしなければ
clickイベントの window.locationイベントのエラーを回避できなかった

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0