[英]Mocking service calls in Jest Tests for StencilJs
In my StencilJs application I am writing tests using Jest.在我的 StencilJs 应用程序中,我正在使用 Jest 编写测试。 I have a component class which uses the Service class to make REST calls.
我有一个组件 class,它使用服务 class 进行 REST 调用。 For simplicity here, the service class just has one method which prints some text:
为简单起见,服务 class 只有一种方法可以打印一些文本:
The Component class:组件 class:
import {sayHello} from './helloworld-service';
@Component({
tag: 'comp-home',
styleUrl: 'comp-home.scss',
shadow: false,
scoped: true
})
export class MyComponent {
public callHelloWorldService () {
return sayHello();
} } } }
The Service class looks like this:服务 class 如下所示:
export function sayHello () {
return "Hello!";
}
It has only one function and I want to mock this function in my test method which is as follows:它只有一个 function,我想在我的测试方法中模拟这个 function,如下所示:
jest.mock('../helloworld/helloworld-service', () => ({
sayHello: jest.fn()
}));
import { sayHello } from '../helloworld/helloworld-service';
const mockSayHello = sayHello as jest.Mock;
describe('mycomp-tests', () => {
let compInstance;
beforeEach(() => {
mockSayHello.mockClear();
compInstance = new MyComponent();
});
afterEach(() => {
jest.clearAllMocks();
});
it('should return mock value', () => {
mockSayHello.mockReturnValue("yahoo");
expect(compInstance.callHelloWorldService()).toBe("yahoo");
});
I have used the this tutorial for https://mikeborozdin.com/post/changing-jest-mocks-between-tests/ writing the mocks.我已将本教程用于https://mikeborozdin.com/post/changing-jest-mocks-between-tests/编写模拟。
Now, the issue I am facing is that if I call mocked service method directly in the test, the mocked instance is called and the test passes:现在,我面临的问题是,如果我在测试中直接调用模拟服务方法,则会调用模拟实例并且测试通过:
it('should return mock value', () => {
mockSayHello.mockReturnValue("yahoo");
expect(compInstance.callHelloWorldService()).toBe("yahoo");
});
But if I call the service method via my component, then the original method in the service is called instead of the mocked method and test fails:但是如果我通过我的组件调用服务方法,那么调用服务中的原始方法而不是模拟方法并且测试失败:
it('should return mock value', () => {
mockSayHello.mockReturnValue("yahoo");
expect(compInstance.callHelloWorldService()).toBe("yahoo");//Fails ,return value is Hello !
});
How can I ensure that the components also call the mocked methods?我如何确保组件也调用模拟方法? This behaviour is needed to mock REST calls in the test etc.
在测试等中模拟 REST 调用需要此行为。
I mocked functions like this in stencil unit tests我在模板单元测试中模拟了这样的函数
import * as HelloworldService from '../helloworld/helloworld-service';
HelloworldService.sayHello = jest.fn().mockReturnValue("yahoo");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.