简体   繁体   English

开玩笑地模拟回调或嵌套函数

[英]Mocking callback or nested function in jest

I have code as,我有代码,

public async waitForElementSelected(element: WebdriverIO.Element) {
    /**
     * Maximum number of milliseconds to wait for
     * @type {Int}
     */
    const ms = 10000;
    await browser.waitUntil(async () =>{
      return element.isSelected();
    },{
      timeout: ms,
      timeoutMsg: 'Condition not met: Element is not selected',
      interval: 100
    });
  }

Here, I have easily tested wait until by mocking the browser, but I am not able to mock "isSelected" or element.isSelected();在这里,我通过模拟浏览器轻松测试了等待,但我无法模拟“isSelected”或 element.isSelected(); line.线。

I have tried, mocking我试过了,嘲笑

global.element = {
      isSelected: jest.fn()
    };

But it is not working as expected, and giving element.isSelected() line still under not covered.但它没有按预期工作,并且仍然没有覆盖 element.isSelected() 行。

Following is my Test case,以下是我的测试用例,

    describe('waitForElementToBeSelected', () => {
  beforeEach(() => {
    mockElement = {
      isSelected: jest.fn()
    };
    mockElement.isSelected.mockReturnValue(true);

    /** **browser mock section ***/
    // global.browser = {
    //   waitUntil: ()=> {
    //     mockElement.isSelected();
    //   }
    // };
  });

  it('should call waitForElementSelected on the browser object', async () => {
    await waitActions.waitForElementToBeSelected(mockElement);
    expect(mockElement.isSelected).toHaveBeenCalled();
    // 
//expect(global.browser.waitUntil).toHaveBeenCalledTimes(1);
  });
});

This code is giving me the error, "browser not defined".这段代码给了我错误,“浏览器未定义”。 If I enabled the code,/** **browser mock section ***/ then, I am getting that, line如果我启用了代码,/** **浏览器模拟部分 ***/ 那么,我明白了,行

return element.isSelected()

is still not getting covered.仍然没有被覆盖。

This is because element is not a global variable, but an argument that you are passing into the waitForElementSelected function.这是因为element不是全局变量,而是您传递给waitForElementSelected函数的参数。 What you need to do instead is pass an object with mock functions when calling it.你需要做的是在调用它时传递一个带有模拟函数的对象。

So in your test you can have it as follows:因此,在您的测试中,您可以使用如下方式:

// mock out the element
const mockElement = {
  isSelected: jest.fn()
};

// mock out the promise response
mockElement.isSelected.mockReturnValue(new Promise((resolve) => resolve(true)));

// call the function
waitForElementSelected(mockElement);

// expect
expect(mockElement.isSelected).toHaveBeenCalled();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM