Jasmine.createSpy 相当于玩笑

olg*_*sta 2 jasmine jestjs

我正在我的应用程序中从 jasmine 迁移到 jest。我有以下行要测试

JSON.parse(window.document.querySelector(SELECTOR).innerHTML)
Run Code Online (Sandbox Code Playgroud)

在我的测试中我使用了茉莉花。

document.querySelector = jasmine.createSpy('HTML Element').and.returnValue(dummyEl)
Run Code Online (Sandbox Code Playgroud)

但现在开玩笑我收到以下错误

TypeError: Cannot read property 'innerHTML' of null
Run Code Online (Sandbox Code Playgroud)

你能帮助我吗?

Ali*_*F50 5

jest.fn我认为你需要和的组合.mockReturnValue

我不太擅长,jest但我认为可以是:

document.querySelector = jest.fn().mockReturnValue(dummyEl);
Run Code Online (Sandbox Code Playgroud)

查看此处的文档:

https://jestjs.io/docs/jest-object#jestfnimplementation

https://jestjs.io/docs/mock-function-api#mockfnmockimplementationfn

  • 我使用了间谍,它也有效。jest.spyOn(document, 'querySelector').mockReturnValue(dummyEl); (3认同)